Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Injecting Function with Puppeteer

I am trying to inject this function to webpage with Puppeteer to get the event listeners of the website.

My code is:

Array.from(document.querySelectorAll('*'))
  .reduce(function(pre, dom){
    var evtObj = getEventListeners(dom)
    Object.keys(evtObj).forEach(function (evt) {
      if (typeof pre[evt] === 'undefined') {
        pre[evt] = 0
      }
      pre[evt] += evtObj[evt].length
    })
    return pre
  }, {})

I have tried to run code below.

'use strict';

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto('https://google.com')
    
    
    var FunctionToInject = function(input){
        Array.from(document.querySelectorAll('*'))
        .reduce(function(pre, dom){
          var evtObj = getEventListeners(dom)
          Object.keys(evtObj).forEach(function (evt) {
            if (typeof pre[evt] === 'undefined') {
              pre[evt] = 0
            }
            pre[evt] += evtObj[evt].length
          })
          return pre
        }, {})
      

    }
    
    await page.exposeFunction('functionToInject', functionToInject);

    
    var data = await page.evaluate(async function(){
        return  await FunctionToInject();
    });
    
    console.log(data);
    

    await browser.close();
})();

I am getting UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: document is not defined error. How can I resolve this issue?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!