Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing outer scope variable in callback

Tags:

puppeteer

I have this ES6 code in Puppeteer:

async function waitForSelectorReversed(page, selector) {
  await page.waitFor(() => !document.querySelector(selector));
}

When I call this code I get the error Evaluation failed: ReferenceError: selector is not defined. I understand that this error is caused by the fact that the code inside the closure can't access the variable from the outer scope. What is a way of getting this to work?

like image 428
SebastianR Avatar asked Mar 10 '26 04:03

SebastianR


1 Answers

You need to explicitly pass outer scope variables into into page.waitFor for it to work. As the documentation states:

To pass arguments from node.js to the predicate of page.waitFor function:

const selector = '.foo';
await page.waitFor(selector => !document.querySelector(selector), {}, selector);

For your code, all you need to do is remove the first line, since selector is already defined.

This isn't so much a plain Javascript thing or an ES6 thing, it's a quirk of how Puppeteer (and Puppeteer-like tools) work when interacting with the page.

like image 198
CertainPerformance Avatar answered Mar 12 '26 21:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!