Playwright wait for function

Playwright’s wait for function:

The wait for function in Playwright is used to wait for a certain condition to be met before proceeding with the execution of further actions. It allows you to wait for an element to appear, disappear, become visible, or become hidden on a webpage.

The basic syntax of the wait for function is as follows:


    await page.waitFor(selectorOrFunction, options);
  

Parameters:

  • selectorOrFunction (required) – It can be a selector string representing the element you want to wait for, or a function that will be executed repeatedly until it returns a truthy value.
  • options (optional) – Additional options for the wait operation, such as timeout (maximum time to wait), pollInterval (interval to check for the condition), etc.

Examples:

  1. Wait for an element to appear:

    
            await page.waitFor('div#myElement');
          

    This will wait until the element with the id “myElement” appears on the page before proceeding with further actions.

  2. Wait for an element to become visible:

    
            await page.waitFor('div#myElement', { state: 'visible' });
          

    This will wait until the element with the id “myElement” becomes visible (i.e., not hidden by CSS properties or parent elements) before proceeding with further actions.

  3. Wait for an element to disappear:

    
            await page.waitFor(() => !document.querySelector('div#myElement'));
          

    This will wait until the element with the id “myElement” disappears from the page before proceeding with further actions.

  4. Wait for a custom condition using a function:

    
            await page.waitFor(() => {
              const element = document.querySelector('div#myElement');
              return element && element.textContent === 'Hello World!';
            });
          

    This will wait until the element with the id “myElement” exists on the page and its text content is “Hello World!” before proceeding with further actions.

Overall, the wait for function in Playwright is extremely useful when dealing with asynchronous web applications or when waiting for certain UI states before performing actions or assertions.

Leave a comment