我正在使用木偶在浏览器中评估codeToBeEvaluated
功能。codeToBeEvaluated
有一个while
循环,应该在每 10 秒后显示一个alert
(见 B 行)。
问题是当我运行此脚本时,我没有看到任何警报。代码执行不会在 A 行中等待 10 秒,而是立即退出进程。我不知道为什么。我真的很好奇为什么它不起作用。
有趣的是,当我只在浏览器控制台中运行codeToBeEvaluated
功能时,它运行良好,并且我看到了我应该看到的警报。
如果有人能解释这种行为,那就太棒了。我不是在寻找任何解决方法来显示警报。我只是想了解这种行为。
const puppeteer = require("puppeteer");
// this function will be executed in the browser
// it should create an alert after some time interval
const codeToBeEvaluated = async () => {
let index_2 = 0;
// a promise that resolves after ms*1000 seconds
async function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// await within function's while loop
async function whileWrapper() {
while (index_2 < 10) {
await sleep(10000); // LINE A: execution doesn't stop at all :/
alert("hello " + index_2); // LINE B: does NOT execute at all
index_2++;
}
}
whileWrapper();
};
async function main(url) {
const browser = await puppeteer.launch({
// headless: false,
devtools: true,
// args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
const page = await browser.newPage();
await page.goto(url);
await page.evaluate(codeToBeEvaluated);
browser.close();
}
main("https://www.google.com/search?q=hello");
在DevTools上手动执行codeToBeEvaluated
与从木偶脚本执行之间的区别在于:
- 在 DevTools 控制台上,脚本有无限的时间来执行更长的异步命令(除非在浏览器仍在运行时快速关闭浏览器)
- 在您的木偶脚本中,您在
page.evaluate
之后还有其他命令,例如browser.close
(我建议您将其放在await
之后,因为它返回一个承诺!),因此浏览器在函数完成之前关闭
您还需要等待whileWrapper()
的承诺,因此将 ROW 25 中的代码更改为以下内容将使其按照您的预期运行:
await whileWrapper();