首页 > 解决方案 > puppeteer 网页异步代码未执行

问题描述

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

节点:

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);   
};

标签: javascriptasynchronouspuppeteer

解决方案


您可以使用page.waitForFunction来收听原始函数的预期结果。像这样,您可以确保只有在应用程序中解决了 Promise之后,下一步 ( page.screenshot) 才会发生。 为此,您可以在顶部声明 URL 参数的值,以便稍后在将其作为参数传递给方法时比较其值。onmount
code=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();
})();

推荐阅读