Unable to wait for the page to load completely

Hi eveyone,

I have been trying to load a page and capture the screenshot. But seems like the page is not loaded yet and the screenshot captured is pure white blank image. Actually the page takes some time to load all of its content.

When I manually opened the same page and checked the Network tab it shows this:

I want to capture the screenshot of page only after the finish time and not after ‘load’ or ‘domcontentloaded’, because only after the finish time, all of my resources have finished loading.

I believe the events available to wait does not have a type of ‘Finish’.
So, only event I think might have helped is ‘networkidle’.

Here is a sample script I am using:

import { chromium } from 'k6/experimental/browser';
import {sleep} from 'k6';
import exec from 'k6/execution';

export default async function () {
  const browser = chromium.launch({
    headless: false,
    timeout: '60s',
  });

  const context = browser.newContext({ ignoreHTTPSErrors: true });
  const page = context.newPage();

  const vuNumber = exec.vu.idInTest;
  

  try {
    await page.goto('https://www.abcd.com',{waitUntil:'networkidle'});
    // page.waitForLoadState('networkidle'); Tried this separately
   // page.waitForNavigation('networkidle'); Tried this separately
    page.screenshot({ path: 'screenshots/browser.png' });
    sleep(5);
  } finally {
    page.close();
    browser.close();
  }
}

The only way I have figured out is to add sleep statement before capturing the screenshot.
Is there an alternative way to achieve this?

Hey @blaZe

Our recommendation is to use the load event for page.goto action (this is the default option). That will make the goto action wait until the load event is fired, which indicates that “the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images”. This, in some cases though, might not include some other elements loaded from a script execution.

There is no such finish event that we can hook to, as you mention.

If some elements of the page are taking longer to fully load, you can try to add a sleep action after the page.goto and before the screenshot. E.g.:

import { chromium } from 'k6/experimental/browser';
import {sleep} from 'k6';

export default async function () {
  const browser = chromium.launch({
    headless: false,
    timeout: '60s',
  });

  const context = browser.newContext({ ignoreHTTPSErrors: true });
  const page = context.newPage();

  try {
    await page.goto('https://www.abcd.com');
    sleep(5);
    page.screenshot({ path: 'screenshots/browser.png' });
  } finally {
    page.close();
    browser.close();
  }
}

Another option would be to use the waitForSelector method and try to wait for the element that’s taking longer to load.