我在 Puppeteer 中有这个 ES6 代码:
async function waitForSelectorReversed(page, selector) {
await page.waitFor(() => !document.querySelector(selector));
}
当我调用此代码时,出现错误 Evaluation failed: ReferenceError: selector is not defined
。我知道这个错误是由于闭包内的代码无法从外部范围访问变量引起的。有什么方法可以让它发挥作用?
最佳答案
您需要显式地将外部作用域变量传递到 page.waitFor
中,它才能工作。作为documentation状态:
To pass arguments from node.js to the predicate of
page.waitFor
function:const selector = '.foo'; await page.waitFor(selector => !document.querySelector(selector), {}, selector);
对于您的代码,您需要做的就是删除第一行,因为已经定义了 selector
。
这与其说是普通的 Javascript 或 ES6,不如说是 Puppeteer(和类似 Puppeteer 的工具)在与页面交互时的工作方式的怪癖。
关于puppeteer - 在回调中访问外部范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53040875/