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?
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.waitForfunction: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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With