×
☰ See All Chapters

Puppeteer waitForFunction

  • page.waitForFunction method waits till the supplied function evaluates to true. 

  •  

waitForFunction(

    fn: PageFunction,

    options ?: PageFnOptions,

    ...args: SerializableOrJSHandle[]

): Promise<JSHandle>;

  • Example: 

const watchDog = page.waitForFunction("document.getElementById('loginUsername').value === 'hello'", {});

const loginUsername = await page.waitForSelector( "#loginUsername", { visible: true } );

await loginUsername.type("hello");

await watchDog;

  • waitForFunction method returns the promise with the JSHandle of the truthy value. 

  • waitForFunction parameters. 

parameter

Description

PageFunction

This Function will be evaluated in browser context.

page.waitForFunction("document.getElementById('loginUsername').value === 'hello'", {});

This function waits till the value of the element with id “loginUsername” become equal to “hello”

PageFnOptions

This should be array waiting parameters. This array allows below options:

polling: An interval at which the PageFunction should be executed in milliseconds.

timeout: This is the maximum time puppeteer wait for the function to get evaluated to true.

args

Arguments to pass to PageFunction

Puppeteer waitForFunction Example

import { launch, Page } from 'puppeteer';

example();

async function example() {

    const browser = await launch( { headless: false } );

    const page = await browser.newPage();

    await page.goto( 'https://www.registration.tools4testing.com/' );

     const watchDog = page.waitForFunction("window.innerWidth > 1365");

    page.setViewport( { width: 1366, height: 768 } );

    await watchDog;

    console.log("waitForFunction complete");

    await login( page );

    await page.waitFor(5000);

    await browser.close();

}

 

async function login( page: Page ): Promise<void> {

    const loginopener = await page.$( "#loginopener" );

    loginopener.click();

    console.log("Login dialog window opened.");

    await page.waitFor(1000);

    const watchDog = page.waitForFunction("document.getElementById('loginUsername').value === 'hello'", {});

    const loginUsername = await page.waitForSelector( "#loginUsername", { visible: true } );

    await loginUsername.type("hello");

    await watchDog;

}

Click here to learn to execute puppeteer example using typescript

 


All Chapters
Author