Puppeteer | Wait for all JavaScript is executed

后端 未结 2 742
栀梦
栀梦 2021-01-11 16:39

I try to take screenshots from multiple pages, which should be fully loaded (including lazy loaded images) for later comparison.

I found the lazyimages_without_scrol

相关标签:
2条回答
  • 2021-01-11 16:45
    async function takeScreenshot(browser, viewport, route) {
      return browser.newPage().then(async (page) => {
        const fileName = `${viewport.directory}/${getFilename(route)}`;
    
        await page.setViewport({
          width: viewport.width,
          height: 500,
        });
        await page.goto(
            `${config.server.master}${route}.html`,
            {
              waitUntil: 'networkidle0',
            }
        );
        await page.evaluate(() => {
          scroll(0, 99999)
        });
        await page.waitFor(5000);
        await page.screenshot({
          path: `screenshots/master/${fileName}.png`,
          fullPage: true,
        });
    
        await page.close();
        console.log(`Viewport "${viewport.name}", Route "${route}"`);
      });
    }
    
    0 讨论(0)
  • 2021-01-11 17:02

    The following waitForFunction might be useful for you, you can use it to wait for any arbitrary function to evaluate to true. If you have access to the page's code you can set the window status and use that to notify puppeteer it is safe to continue, or just rely on some sort of other ready state. Note: this function is a polling function, and re-evaluates at some interval which can be specified.

    const watchDog = page.waitForFunction('<your function to evaluate to true>');
    

    E.g.,

    const watchDog = page.waitForFunction('window.status === "ready"');
    await watchDog;
    

    In your page's code you simply need to set the window.status to ready

    To utilize multiple watchdogs in multiple asynchronous files you could do something like

    index.js

    ...import/require file1.js;
    ...import/require file2.js;
    ...code...
    

    file1.js:

    var file1Flag=false; // global
    ...code...
    file1Flag=true;
    

    file2.js:

    var file2Flag=false; // global
    ...code...
    file2Flag=true;
    

    main.js:

    const watchDog = page.waitForFunction('file1Flag && file2Flag');
    await watchDog;
    
    0 讨论(0)
提交回复
热议问题