【问题标题】:puppeteer web page async code not executedpuppeteer 网页异步代码未执行
【发布时间】:2021-07-10 21:45:50
【问题描述】:

如果我“转到”包含异步代码的网页,它不会被执行,我不明白为什么。有人可以帮忙吗?

节点:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://127.0.0.1:8080/?code=ABC123&id=1', {
    waitUntil: 'networkidle0',
  });
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();

网页:

onmount = () => {
    const params = new URLSearchParams(document.location.search);
    const code = params.get('code');
    // above lines are executed     
   
    // the code below is never executed
    // search is an async function (not shown for brevity)
    search(code).then(result => document.getElementById('title').textContent = result.title);   
};

【问题讨论】:

  • 如果您手动访问您的应用程序,它可以工作吗?
  • “未执行”是指屏幕截图和浏览器的关闭发生在标题 textContent 更新之前?
  • @vinicious 网页代码在浏览器中按预期工作
  • @theDavidBarton 我不确定异步代码是否正在执行。如果是,则 Chromium / puppeteer 不会等待它
  • 重读@theDavidBarton 的问题和我的回答后,异步代码正在执行但在 Chromium 中没有等待更有意义。它在浏览器中执行和等待,所以我不明白为什么它不在 Chromium 中?

标签: javascript asynchronous puppeteer


【解决方案1】:

您可以使用page.waitForFunction 来监听原始函数的预期结果。像这样,您可以确保只有在应用程序中解决了 onmount 承诺后才会执行下一步 (page.screenshot)。
为此,您可以在顶部声明code= URL 参数的值,以便稍后在将其作为参数传递给waitForFunction 方法时比较其值。

await page.waitForFunction(codeValue => document.querySelector('#title').textContent == codeValue, {}, codeValue);

例子:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  const codeValue = 'ABC123';
  await page.goto(`http://127.0.0.1:8080/?code=${codeValue}&id=1`, {
    waitUntil: 'networkidle0',
  });

  await page.waitForFunction(codeValue => document.querySelector('#title').textContent == codeValue, {}, codeValue);
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();

【讨论】:

  • 感谢您抽出宝贵时间回答这个问题。该问题与引发异常并阻止异步代码解析的 api 调用有关。我将关闭这个问题。为浪费任何人的时间而道歉
  • 解决一般问题不会浪费时间?我认为您可以保留问题,因为它稍后可以获得一些一般性答案(就像我的回答一样)。您可能不接受它们 - 因为您的解决方案有点特定于您的站点/环境 - 其他人仍然会发现问题和收到的答案很有用。
猜你喜欢
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多