0

When the following build runs, I get the error "Error: Evaluation failed: ReferenceError: chunk is not defined" as a console response. In the next line, I can reach chunk[a] as console.log, but why can't I reach it in frame.evaluate?

const puppeteer = require('puppeteer');
const chunk= ["google.com","facebook.com","gmail.com","stackoverflow.com"];

(async () => {
    for(var a=0;a<chunk.length;a++){
      const browser = await puppeteer.launch({headless:false})
      const page = await browser.newPage();
      const iframeHandle = await page.$("frame[name='main']");
      const frame = await iframeHandle.contentFrame();
      console.log(chunk[a]);
      await frame.evaluate(() => {
        if(document.querySelector("#content > table").innerHTML.indexOf(chunk[a]) > -1){
            console.log(chunk[a]);
        }
      });
    }
})()

result : google.com Evaluation failed: ReferenceError: chunk is not defined

  • The callback to `evaluate` is serialized and executed in the browser console. That's a totally separate process than your Node app, so you have to pass serializable data to it using the `args` parameter described in the [docs](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#frameevaluatepagefunction-args), `frame.evaluate(chunk => {...}, chunks[a])` (I'd pluralize `chunk` since it's an array). – ggorlen Oct 05 '21 at 15:07

1 Answers1

0

I moved the chunck inside the async and chunk is not defined disappeared. However, this time another error occured regarding the element you want to reach. I tried to correct this as well by adding .waitForSelector and removing page.$ but a third error occured which I believe is because of mispelled element path ("frame[name='main']"). You may change it and try it with the code below:

  (async () => {
    const chunk= ["google.com","facebook.com","gmail.com","stackoverflow.com"];
    for(var a=0;a<chunk.length;a++){
      const browser = await puppeteer.launch({headless:false})
      const page = await browser.newPage();
      const iframeHandle = await page.waitForSelector("frame[name='main']");
      const frame = await iframeHandle.contentFrame();
      console.log(chunk[a]);
      await frame.evaluate(() => {
        if(document.querySelector("#content > table").innerHTML.indexOf(chunk[a]) > -1){
            console.log(chunk[a]);
        }
      });
    }
  })()
Abdulhakim
  • 620
  • 8
  • 11