Interface Frame

At every point of time, page exposes its current frame tree via the page.mainFrame() and frame.childFrames() methods.

Frame object's lifecycle is controlled by three events, dispatched on the page object:

An example of dumping frame tree:

const { firefox } = require('playwright');  // Or 'chromium' or 'webkit'.

(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
await page.goto('https://www.google.com/chrome/browser/canary.html');
dumpFrameTree(page.mainFrame(), '');
await browser.close();

function dumpFrameTree(frame, indent) {
console.log(indent + frame.url());
for (const child of frame.childFrames())
dumpFrameTree(child, indent + ' ');
}
})();

Hierarchy

  • Frame

Methods

  • NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.

    Returns the ElementHandle pointing to the frame element.

    NOTE The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead.

    The method finds an element matching the specified selector within the frame. If no elements match the selector, returns null.

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    Parameters

    • selector: K

      A selector to query for.

    • Optional options: {
          strict: boolean;
      }
      Optional
      • strict: boolean

    Returns Promise<ElementHandleForTag<K>>

  • NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.

    Returns the ElementHandle pointing to the frame element.

    NOTE The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead.

    The method finds an element matching the specified selector within the frame. If no elements match the selector, returns null.

    Parameters

    • selector: string

      A selector to query for.

    • Optional options: {
          strict: boolean;
      }
      Optional
      • strict: boolean

    Returns Promise<ElementHandle<HTMLElement | SVGElement>>

  • NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.

    Returns the ElementHandles pointing to the frame elements.

    NOTE The use of ElementHandle is discouraged, use Locator objects instead.

    The method finds all elements matching the specified selector within the frame. If no elements match the selector, returns empty array.

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    Parameters

    • selector: K

      A selector to query for.

    Returns Promise<ElementHandleForTag<K>[]>

  • NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.

    Returns the ElementHandles pointing to the frame elements.

    NOTE The use of ElementHandle is discouraged, use Locator objects instead.

    The method finds all elements matching the specified selector within the frame. If no elements match the selector, returns empty array.

    Parameters

    • selector: string

      A selector to query for.

    Returns Promise<ElementHandle<HTMLElement | SVGElement>[]>

  • NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.

    Returns the return value of pageFunction.

    The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to pageFunction.

    If pageFunction returns a [Promise], then frame.$$eval(selector, pageFunction[, arg]) would wait for the promise to resolve and return its value.

    Usage

    const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
    

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    • R

    • Arg

    Parameters

    • selector: K

      A selector to query for.

    • pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], Arg, R>

      Function to be evaluated in the page context.

    • arg: Arg

      Optional argument to pass to pageFunction.

    Returns Promise<R>

  • NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.

    Returns the return value of pageFunction.

    The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to pageFunction.

    If pageFunction returns a [Promise], then frame.$$eval(selector, pageFunction[, arg]) would wait for the promise to resolve and return its value.

    Usage

    const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
    

    Type Parameters

    • R

    • Arg

    • E extends HTMLElement | SVGElement = HTMLElement | SVGElement

    Parameters

    • selector: string

      A selector to query for.

    • pageFunction: PageFunctionOn<E[], Arg, R>

      Function to be evaluated in the page context.

    • arg: Arg

      Optional argument to pass to pageFunction.

    Returns Promise<R>

  • NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.

    Returns the return value of pageFunction.

    The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to pageFunction.

    If pageFunction returns a [Promise], then frame.$$eval(selector, pageFunction[, arg]) would wait for the promise to resolve and return its value.

    Usage

    const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
    

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    • R

    Parameters

    • selector: K

      A selector to query for.

    • pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], void, R>

      Function to be evaluated in the page context.

    • Optional arg: any

      Optional argument to pass to pageFunction.

      Optional

    Returns Promise<R>

  • NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.

    Returns the return value of pageFunction.

    The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to pageFunction.

    If pageFunction returns a [Promise], then frame.$$eval(selector, pageFunction[, arg]) would wait for the promise to resolve and return its value.

    Usage

    const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
    

    Type Parameters

    • R

    • E extends HTMLElement | SVGElement = HTMLElement | SVGElement

    Parameters

    • selector: string

      A selector to query for.

    • pageFunction: PageFunctionOn<E[], void, R>

      Function to be evaluated in the page context.

    • Optional arg: any

      Optional argument to pass to pageFunction.

      Optional

    Returns Promise<R>

  • NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.

    Returns the return value of pageFunction.

    The method finds an element matching the specified selector within the frame and passes it as a first argument to pageFunction. If no elements match the selector, the method throws an error.

    If pageFunction returns a [Promise], then frame.$eval(selector, pageFunction[, arg, options]) would wait for the promise to resolve and return its value.

    Usage

    const searchValue = await frame.$eval('#search', el => el.value);
    const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
    const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    • R

    • Arg

    Parameters

    • selector: K

      A selector to query for.

    • pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], Arg, R>

      Function to be evaluated in the page context.

    • arg: Arg

      Optional argument to pass to pageFunction.

    Returns Promise<R>

  • NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.

    Returns the return value of pageFunction.

    The method finds an element matching the specified selector within the frame and passes it as a first argument to pageFunction. If no elements match the selector, the method throws an error.

    If pageFunction returns a [Promise], then frame.$eval(selector, pageFunction[, arg, options]) would wait for the promise to resolve and return its value.

    Usage

    const searchValue = await frame.$eval('#search', el => el.value);
    const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
    const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');

    Type Parameters

    • R

    • Arg

    • E extends HTMLElement | SVGElement = HTMLElement | SVGElement

    Parameters

    • selector: string

      A selector to query for.

    • pageFunction: PageFunctionOn<E, Arg, R>

      Function to be evaluated in the page context.

    • arg: Arg

      Optional argument to pass to pageFunction.

    Returns Promise<R>

  • NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.

    Returns the return value of pageFunction.

    The method finds an element matching the specified selector within the frame and passes it as a first argument to pageFunction. If no elements match the selector, the method throws an error.

    If pageFunction returns a [Promise], then frame.$eval(selector, pageFunction[, arg, options]) would wait for the promise to resolve and return its value.

    Usage

    const searchValue = await frame.$eval('#search', el => el.value);
    const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
    const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    • R

    Parameters

    • selector: K

      A selector to query for.

    • pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], void, R>

      Function to be evaluated in the page context.

    • Optional arg: any

      Optional argument to pass to pageFunction.

      Optional

    Returns Promise<R>

  • NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.

    Returns the return value of pageFunction.

    The method finds an element matching the specified selector within the frame and passes it as a first argument to pageFunction. If no elements match the selector, the method throws an error.

    If pageFunction returns a [Promise], then frame.$eval(selector, pageFunction[, arg, options]) would wait for the promise to resolve and return its value.

    Usage

    const searchValue = await frame.$eval('#search', el => el.value);
    const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
    const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');

    Type Parameters

    • R

    • E extends HTMLElement | SVGElement = HTMLElement | SVGElement

    Parameters

    • selector: string

      A selector to query for.

    • pageFunction: PageFunctionOn<E, void, R>

      Function to be evaluated in the page context.

    • Optional arg: any

      Optional argument to pass to pageFunction.

      Optional

    Returns Promise<R>

  • Returns the added tag when the script's onload fires or when the script content was injected into frame.

    Adds a <script> tag into the page with the desired url or content.

    Parameters

    • Optional options: {
          content?: string;
          path?: string;
          type?: string;
          url?: string;
      }
      Optional
      • Optional content?: string

        Raw JavaScript content to be injected into frame.

      • Optional path?: string

        Path to the JavaScript file to be injected into frame. If path is a relative path, then it is resolved relative to the current working directory.

      • Optional type?: string

        Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.

      • Optional url?: string

        URL of a script to be added.

    Returns Promise<ElementHandle<Node>>

  • Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

    Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content.

    Parameters

    • Optional options: {
          content?: string;
          path?: string;
          url?: string;
      }
      Optional
      • Optional content?: string

        Raw CSS content to be injected into frame.

      • Optional path?: string

        Path to the CSS file to be injected into frame. If path is a relative path, then it is resolved relative to the current working directory.

      • Optional url?: string

        URL of the <link> tag.

    Returns Promise<ElementHandle<Node>>

  • NOTE Use locator-based locator.check([options]) instead. Read more about locators.

    This method checks an element matching selector by performing the following steps:

    1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
    2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
    3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
    4. Scroll the element into view if needed.
    5. Use page.mouse to click in the center of the element.
    6. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
    7. Ensure that the element is now checked. If not, this method throws.

    When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          force?: boolean;
          noWaitAfter?: boolean;
          position?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional position?: {
            x: number;
            y: number;
        }

        A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • Returns Frame[]

  • NOTE Use locator-based locator.click([options]) instead. Read more about locators.

    This method clicks an element matching selector by performing the following steps:

    1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
    2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
    3. Scroll the element into view if needed.
    4. Use page.mouse to click in the center of the element, or the specified position.
    5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

    When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          button?: "left" | "right" | "middle";
          clickCount?: number;
          delay?: number;
          force?: boolean;
          modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[];
          noWaitAfter?: boolean;
          position?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional button?: "left" | "right" | "middle"

        Defaults to left.

      • Optional clickCount?: number

        defaults to 1. See [UIEvent.detail].

      • Optional delay?: number

        Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.

      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]

        Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional position?: {
            x: number;
            y: number;
        }

        A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • Gets the full HTML contents of the frame, including the doctype.

    Returns Promise<string>

  • NOTE Use locator-based locator.dblclick([options]) instead. Read more about locators.

    This method double clicks an element matching selector by performing the following steps:

    1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
    2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
    3. Scroll the element into view if needed.
    4. Use page.mouse to double click in the center of the element, or the specified position.
    5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set. Note that if the first click of the dblclick() triggers a navigation event, this method will throw.

    When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

    NOTE frame.dblclick() dispatches two click events and a single dblclick event.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          button?: "left" | "right" | "middle";
          delay?: number;
          force?: boolean;
          modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[];
          noWaitAfter?: boolean;
          position?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional button?: "left" | "right" | "middle"

        Defaults to left.

      • Optional delay?: number

        Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.

      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]

        Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional position?: {
            x: number;
            y: number;
        }

        A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • NOTE Use locator-based locator.dispatchEvent(type[, eventInit, options]) instead. Read more about locators.

    The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is dispatched. This is equivalent to calling element.click().

    Usage

    await frame.dispatchEvent('button#submit', 'click');
    

    Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

    Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

    You can also specify JSHandle as the property value if you want live objects to be passed into the event:

    // Note you can only create DataTransfer in Chromium and Firefox
    const dataTransfer = await frame.evaluateHandle(() => new DataTransfer());
    await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • type: string

      DOM event type: "click", "dragstart", etc.

    • Optional eventInit: EvaluationArgument

      Optional event-specific initialization properties.

      Optional
    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<void>

  • Parameters

    • source: string

      A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.

    • target: string

      A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          force?: boolean;
          noWaitAfter?: boolean;
          sourcePosition?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          targetPosition?: {
              x: number;
              y: number;
          };
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional sourcePosition?: {
            x: number;
            y: number;
        }

        Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional targetPosition?: {
            x: number;
            y: number;
        }

        Drops on the target element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.

        • x: number
        • y: number
      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • Returns the return value of pageFunction.

    If the function passed to the frame.evaluate(pageFunction[, arg]) returns a [Promise], then frame.evaluate(pageFunction[, arg]) would wait for the promise to resolve and return its value.

    If the function passed to the frame.evaluate(pageFunction[, arg]) returns a non-[Serializable] value, then frame.evaluate(pageFunction[, arg]) returns undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.

    Usage

    const result = await frame.evaluate(([x, y]) => {
    return Promise.resolve(x * y);
    }, [7, 8]);
    console.log(result); // prints "56"

    A string can also be passed in instead of a function.

    console.log(await frame.evaluate('1 + 2')); // prints "3"
    

    ElementHandle instances can be passed as an argument to the frame.evaluate(pageFunction[, arg]):

    const bodyHandle = await frame.evaluate('document.body');
    const html = await frame.evaluate(([body, suffix]) =>
    body.innerHTML + suffix, [bodyHandle, 'hello'],
    );
    await bodyHandle.dispose();

    Type Parameters

    • R

    • Arg

    Parameters

    • pageFunction: PageFunction<Arg, R>

      Function to be evaluated in the page context.

    • arg: Arg

      Optional argument to pass to pageFunction.

    Returns Promise<R>

  • Returns the return value of pageFunction.

    If the function passed to the frame.evaluate(pageFunction[, arg]) returns a [Promise], then frame.evaluate(pageFunction[, arg]) would wait for the promise to resolve and return its value.

    If the function passed to the frame.evaluate(pageFunction[, arg]) returns a non-[Serializable] value, then frame.evaluate(pageFunction[, arg]) returns undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.

    Usage

    const result = await frame.evaluate(([x, y]) => {
    return Promise.resolve(x * y);
    }, [7, 8]);
    console.log(result); // prints "56"

    A string can also be passed in instead of a function.

    console.log(await frame.evaluate('1 + 2')); // prints "3"
    

    ElementHandle instances can be passed as an argument to the frame.evaluate(pageFunction[, arg]):

    const bodyHandle = await frame.evaluate('document.body');
    const html = await frame.evaluate(([body, suffix]) =>
    body.innerHTML + suffix, [bodyHandle, 'hello'],
    );
    await bodyHandle.dispose();

    Type Parameters

    • R

    Parameters

    • pageFunction: PageFunction<void, R>

      Function to be evaluated in the page context.

    • Optional arg: any

      Optional argument to pass to pageFunction.

      Optional

    Returns Promise<R>

  • Returns the return value of pageFunction as a JSHandle.

    The only difference between frame.evaluate(pageFunction[, arg]) and frame.evaluateHandle(pageFunction[, arg]) is that frame.evaluateHandle(pageFunction[, arg]) returns JSHandle.

    If the function, passed to the frame.evaluateHandle(pageFunction[, arg]), returns a [Promise], then frame.evaluateHandle(pageFunction[, arg]) would wait for the promise to resolve and return its value.

    Usage

    // Handle for the window object
    const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));

    A string can also be passed in instead of a function.

    const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.
    

    JSHandle instances can be passed as an argument to the frame.evaluateHandle(pageFunction[, arg]):

    const aHandle = await frame.evaluateHandle(() => document.body);
    const resultHandle = await frame.evaluateHandle(([body, suffix]) =>
    body.innerHTML + suffix, [aHandle, 'hello'],
    );
    console.log(await resultHandle.jsonValue());
    await resultHandle.dispose();

    Type Parameters

    • R

    • Arg

    Parameters

    • pageFunction: PageFunction<Arg, R>

      Function to be evaluated in the page context.

    • arg: Arg

      Optional argument to pass to pageFunction.

    Returns Promise<SmartHandle<R>>

  • Returns the return value of pageFunction as a JSHandle.

    The only difference between frame.evaluate(pageFunction[, arg]) and frame.evaluateHandle(pageFunction[, arg]) is that frame.evaluateHandle(pageFunction[, arg]) returns JSHandle.

    If the function, passed to the frame.evaluateHandle(pageFunction[, arg]), returns a [Promise], then frame.evaluateHandle(pageFunction[, arg]) would wait for the promise to resolve and return its value.

    Usage

    // Handle for the window object
    const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));

    A string can also be passed in instead of a function.

    const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.
    

    JSHandle instances can be passed as an argument to the frame.evaluateHandle(pageFunction[, arg]):

    const aHandle = await frame.evaluateHandle(() => document.body);
    const resultHandle = await frame.evaluateHandle(([body, suffix]) =>
    body.innerHTML + suffix, [aHandle, 'hello'],
    );
    console.log(await resultHandle.jsonValue());
    await resultHandle.dispose();

    Type Parameters

    • R

    Parameters

    • pageFunction: PageFunction<void, R>

      Function to be evaluated in the page context.

    • Optional arg: any

      Optional argument to pass to pageFunction.

      Optional

    Returns Promise<SmartHandle<R>>

  • NOTE Use locator-based locator.fill(value[, options]) instead. Read more about locators.

    This method waits for an element matching selector, waits for actionability checks, focuses the element, fills it and triggers an input event after filling. Note that you can pass an empty string to clear the input field.

    If the target element is not an <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.

    To send fine-grained keyboard events, use locator.pressSequentially(text[, options]).

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • value: string

      Value to fill for the <input>, <textarea> or [contenteditable] element.

    • Optional options: {
          force?: boolean;
          noWaitAfter?: boolean;
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<void>

  • NOTE Use locator-based locator.focus([options]) instead. Read more about locators.

    This method fetches an element with selector and focuses it. If there's no element matching selector, the method waits until a matching element appears in the DOM.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<void>

  • Returns the frame or iframe element handle which corresponds to this frame.

    This is an inverse of elementHandle.contentFrame(). Note that returned handle actually belongs to the parent frame.

    This method throws an error if the frame has been detached before frameElement() returns.

    Usage

    const frameElement = await frame.frameElement();
    const contentFrame = await frameElement.contentFrame();
    console.log(frame === contentFrame); // -> true

    Returns Promise<ElementHandle<Node>>

  • When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.

    Usage

    Following snippet locates element with text "Submit" in the iframe with id my-frame, like <iframe id="my-frame">:

    const locator = frame.frameLocator('#my-iframe').getByText('Submit');
    await locator.click();

    Parameters

    • selector: string

      A selector to use when resolving DOM element.

    Returns FrameLocator

  • NOTE Use locator-based locator.getAttribute(name[, options]) instead. Read more about locators.

    Returns element attribute value.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • name: string

      Attribute name to get the value for.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<string>

  • Allows locating elements by their alt text.

    Usage

    For example, this method will find the image by alt text "Playwright logo":

    <img alt='Playwright logo'>
    
    await page.getByAltText('Playwright logo').click();
    

    Parameters

    • text: string | RegExp

      Text to locate the element for.

    • Optional options: {
          exact?: boolean;
      }
      Optional
      • Optional exact?: boolean

        Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

    Returns Locator

  • Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.

    Usage

    For example, this method will find inputs by label "Username" and "Password" in the following DOM:

    <input aria-label="Username">
    <label for="password-input">Password:</label>
    <input id="password-input">
    await page.getByLabel('Username').fill('john');
    await page.getByLabel('Password').fill('secret');

    Parameters

    • text: string | RegExp

      Text to locate the element for.

    • Optional options: {
          exact?: boolean;
      }
      Optional
      • Optional exact?: boolean

        Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

    Returns Locator

  • Allows locating input elements by the placeholder text.

    Usage

    For example, consider the following DOM structure.

    <input type="email" placeholder="name@example.com" />
    

    You can fill the input after locating it by the placeholder text:

    await page
    .getByPlaceholder('name@example.com')
    .fill('playwright@microsoft.com');

    Parameters

    • text: string | RegExp

      Text to locate the element for.

    • Optional options: {
          exact?: boolean;
      }
      Optional
      • Optional exact?: boolean

        Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

    Returns Locator

  • Allows locating elements by their ARIA role, ARIA attributes and accessible name.

    Usage

    Consider the following DOM structure.

    <h3>Sign up</h3>
    <label>
    <input type="checkbox" /> Subscribe
    </label>
    <br/>
    <button>Submit</button>

    You can locate each element by it's implicit role:

    await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();

    await page.getByRole('checkbox', { name: 'Subscribe' }).check();

    await page.getByRole('button', { name: /submit/i }).click();

    Details

    Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.

    Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines do not recommend duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.

    Parameters

    • role: "search" | "link" | "document" | "status" | "log" | "list" | "code" | "group" | "article" | "blockquote" | "button" | "caption" | "dialog" | "figure" | "form" | "img" | "main" | "menu" | "meter" | "option" | "strong" | "table" | "time" | "scrollbar" | "menuitem" | "switch" | "none" | "timer" | "alert" | "alertdialog" | "application" | "banner" | "cell" | "checkbox" | "columnheader" | "combobox" | "complementary" | "contentinfo" | "definition" | "deletion" | "directory" | "emphasis" | "feed" | "generic" | "grid" | "gridcell" | "heading" | "insertion" | "listbox" | "listitem" | "marquee" | "math" | "menubar" | "menuitemcheckbox" | "menuitemradio" | "navigation" | "note" | "paragraph" | "presentation" | "progressbar" | "radio" | "radiogroup" | "region" | "row" | "rowgroup" | "rowheader" | "searchbox" | "separator" | "slider" | "spinbutton" | "subscript" | "superscript" | "tab" | "tablist" | "tabpanel" | "term" | "textbox" | "toolbar" | "tooltip" | "tree" | "treegrid" | "treeitem"

      Required aria role.

    • Optional options: {
          checked?: boolean;
          disabled?: boolean;
          exact?: boolean;
          expanded?: boolean;
          includeHidden?: boolean;
          level?: number;
          name?: string | RegExp;
          pressed?: boolean;
          selected?: boolean;
      }
      Optional
      • Optional checked?: boolean

        An attribute that is usually set by aria-checked or native <input type=checkbox> controls.

        Learn more about aria-checked.

      • Optional disabled?: boolean

        An attribute that is usually set by aria-disabled or disabled.

        NOTE Unlike most other attributes, disabled is inherited through the DOM hierarchy. Learn more about aria-disabled.

      • Optional exact?: boolean

        Whether name is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when name is a regular expression. Note that exact match still trims whitespace.

      • Optional expanded?: boolean

        An attribute that is usually set by aria-expanded.

        Learn more about aria-expanded.

      • Optional includeHidden?: boolean

        Option that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector.

        Learn more about aria-hidden.

      • Optional level?: number

        A number attribute that is usually present for roles heading, listitem, row, treeitem, with default values for <h1>-<h6> elements.

        Learn more about aria-level.

      • Optional name?: string | RegExp

        Option to match the accessible name. By default, matching is case-insensitive and searches for a substring, use exact to control this behavior.

        Learn more about accessible name.

      • Optional pressed?: boolean

        An attribute that is usually set by aria-pressed.

        Learn more about aria-pressed.

      • Optional selected?: boolean

        An attribute that is usually set by aria-selected.

        Learn more about aria-selected.

    Returns Locator

  • Locate element by the test id.

    Usage

    Consider the following DOM structure.

    <button data-testid="directions">Itinéraire</button>
    

    You can locate the element by it's test id:

    await page.getByTestId('directions').click();
    

    Details

    By default, the data-testid attribute is used as a test id. Use selectors.setTestIdAttribute(attributeName) to configure a different test id attribute if necessary.

    // Set custom test id attribute from @playwright/test config:
    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    use: {
    testIdAttribute: 'data-pw'
    },
    });

    Parameters

    • testId: string | RegExp

      Id to locate the element by.

    Returns Locator

  • Allows locating elements that contain given text.

    See also locator.filter([options]) that allows to match by another criteria, like an accessible role, and then filter by the text content.

    Usage

    Consider the following DOM structure:

    <div>Hello <span>world</span></div>
    <div>Hello</div>

    You can locate by text substring, exact string, or a regular expression:

    // Matches <span>
    page.getByText('world');

    // Matches first <div>
    page.getByText('Hello world');

    // Matches second <div>
    page.getByText('Hello', { exact: true });

    // Matches both <div>s
    page.getByText(/Hello/);

    // Matches second <div>
    page.getByText(/^hello$/i);

    Details

    Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

    Input elements of the type button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.

    Parameters

    • text: string | RegExp

      Text to locate the element for.

    • Optional options: {
          exact?: boolean;
      }
      Optional
      • Optional exact?: boolean

        Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

    Returns Locator

  • Allows locating elements by their title attribute.

    Usage

    Consider the following DOM structure.

    <span title='Issues count'>25 issues</span>
    

    You can check the issues count after locating it by the title text:

    await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
    

    Parameters

    • text: string | RegExp

      Text to locate the element for.

    • Optional options: {
          exact?: boolean;
      }
      Optional
      • Optional exact?: boolean

        Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.

    Returns Locator

  • Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

    The method will throw an error if:

    • there's an SSL error (e.g. in case of self-signed certificates).
    • target URL is invalid.
    • the timeout is exceeded during navigation.
    • the remote server does not respond or is unreachable.
    • the main resource failed to load.

    The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling response.status().

    NOTE The method either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.

    NOTE Headless mode doesn't support navigation to a PDF document. See the upstream issue.

    Parameters

    • url: string

      URL to navigate frame to. The url should include scheme, e.g. https://.

    • Optional options: {
          referer?: string;
          timeout?: number;
          waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
      }
      Optional
      • Optional referer?: string

        Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders(headers).

      • Optional timeout?: number

        Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(timeout), browserContext.setDefaultTimeout(timeout), page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit"

        When to consider operation succeeded, defaults to load. Events can be either:

        • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
        • 'load' - consider operation to be finished when the load event is fired.
        • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
        • 'commit' - consider operation to be finished when network response is received and the document started loading.

    Returns Promise<Response>

  • NOTE Use locator-based locator.hover([options]) instead. Read more about locators.

    This method hovers over an element matching selector by performing the following steps:

    1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
    2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
    3. Scroll the element into view if needed.
    4. Use page.mouse to hover over the center of the element, or the specified position.
    5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

    When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          force?: boolean;
          modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[];
          noWaitAfter?: boolean;
          position?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]

        Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional position?: {
            x: number;
            y: number;
        }

        A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • NOTE Use locator-based locator.innerHTML([options]) instead. Read more about locators.

    Returns element.innerHTML.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<string>

  • NOTE Use locator-based locator.innerText([options]) instead. Read more about locators.

    Returns element.innerText.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<string>

  • NOTE Use locator-based locator.inputValue([options]) instead. Read more about locators.

    Returns input.value for the selected <input> or <textarea> or <select> element.

    Throws for non-input elements. However, if the element is inside the <label> element that has an associated control, returns the value of the control.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<string>

  • NOTE Use locator-based locator.isChecked([options]) instead. Read more about locators.

    Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<boolean>

  • Returns true if the frame has been detached, or false otherwise.

    Returns boolean

  • NOTE Use locator-based locator.isDisabled([options]) instead. Read more about locators.

    Returns whether the element is disabled, the opposite of enabled.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<boolean>

  • NOTE Use locator-based locator.isEditable([options]) instead. Read more about locators.

    Returns whether the element is editable.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<boolean>

  • Returns whether the element is enabled.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<boolean>

  • NOTE Use locator-based locator.isHidden([options]) instead. Read more about locators.

    Returns whether the element is hidden, the opposite of visible. selector that does not match any elements is considered hidden.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Deprecated

        This option is ignored. frame.isHidden(selector[, options]) does not wait for the element to become hidden and returns immediately.

    Returns Promise<boolean>

  • NOTE Use locator-based locator.isVisible([options]) instead. Read more about locators.

    Returns whether the element is visible. selector that does not match any elements is considered not visible.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Deprecated

        This option is ignored. frame.isVisible(selector[, options]) does not wait for the element to become visible and returns immediately.

    Returns Promise<boolean>

  • The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.

    Learn more about locators.

    Learn more about locators.

    Parameters

    • selector: string

      A selector to use when resolving DOM element.

    • Optional options: {
          has?: Locator;
          hasNot?: Locator;
          hasNotText?: string | RegExp;
          hasText?: string | RegExp;
      }
      Optional
      • Optional has?: Locator

        Narrows down the results of the method to those which contain elements matching this relative locator. For example, article that has text=Playwright matches <article><div>Playwright</div></article>.

        Inner locator must be relative to the outer locator and is queried starting with the outer locator match, not the document root. For example, you can find content that has div in <article><content><div>Playwright</div></content></article>. However, looking for content that has article div will fail, because the inner locator must be relative and should not use any elements outside the content.

        Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.

      • Optional hasNot?: Locator

        Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the outer one. For example, article that does not have div matches <article><span>Playwright</span></article>.

        Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.

      • Optional hasNotText?: string | RegExp

        Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element. When passed a [string], matching is case-insensitive and searches for a substring.

      • Optional hasText?: string | RegExp

        Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When passed a [string], matching is case-insensitive and searches for a substring. For example, "Playwright" matches <article><div>Playwright</div></article>.

    Returns Locator

  • Returns frame's name attribute as specified in the tag.

    If the name is empty, returns the id attribute instead.

    NOTE This value is calculated once when the frame is created, and will not update if the attribute is changed later.

    Returns string

  • Returns the page containing this frame.

    Returns Page

  • Parent frame, if any. Detached frames and main frames return null.

    Returns Frame

  • NOTE Use locator-based locator.press(key[, options]) instead. Read more about locators.

    key can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the key values can be found here. Examples of the keys are:

    F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

    Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta. ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS.

    Holding down Shift will type the text that corresponds to the key in the upper case.

    If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

    Shortcuts such as key: "Control+o", key: "Control++ or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • key: string

      Name of the key to press or a character to generate, such as ArrowLeft or a.

    • Optional options: {
          delay?: number;
          noWaitAfter?: boolean;
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional delay?: number

        Time to wait between keydown and keyup in milliseconds. Defaults to 0.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<void>

  • NOTE Use locator-based locator.selectOption(values[, options]) instead. Read more about locators.

    This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

    If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

    Returns the array of option values that have been successfully selected.

    Triggers a change and input event once all the provided options have been selected.

    Usage

    // Single selection matching the value or label
    frame.selectOption('select#colors', 'blue');

    // single selection matching both the value and the label
    frame.selectOption('select#colors', { label: 'Blue' });

    // multiple selection
    frame.selectOption('select#colors', 'red', 'green', 'blue');

    Parameters

    • selector: string

      A selector to query for.

    • values: string | readonly string[] | ElementHandle<Node> | readonly ElementHandle<Node>[] | {
          index?: number;
          label?: string;
          value?: string;
      } | readonly {
          index?: number;
          label?: string;
          value?: string;
      }[]

      Options to select. If the <select> has the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.

    • Optional options: {
          force?: boolean;
          noWaitAfter?: boolean;
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<string[]>

  • NOTE Use locator-based locator.setChecked(checked[, options]) instead. Read more about locators.

    This method checks or unchecks an element matching selector by performing the following steps:

    1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
    2. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
    3. If the element already has the right checked state, this method returns immediately.
    4. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
    5. Scroll the element into view if needed.
    6. Use page.mouse to click in the center of the element.
    7. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
    8. Ensure that the element is now checked or unchecked. If not, this method throws.

    When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • checked: boolean

      Whether to check or uncheck the checkbox.

    • Optional options: {
          force?: boolean;
          noWaitAfter?: boolean;
          position?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional position?: {
            x: number;
            y: number;
        }

        A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • This method internally calls document.write(), inheriting all its specific characteristics and behaviors.

    Parameters

    • html: string

      HTML markup to assign to the page.

    • Optional options: {
          timeout?: number;
          waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
      }
      Optional
      • Optional timeout?: number

        Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(timeout), browserContext.setDefaultTimeout(timeout), page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit"

        When to consider operation succeeded, defaults to load. Events can be either:

        • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
        • 'load' - consider operation to be finished when the load event is fired.
        • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
        • 'commit' - consider operation to be finished when network response is received and the document started loading.

    Returns Promise<void>

  • NOTE Use locator-based locator.setInputFiles(files[, options]) instead. Read more about locators.

    Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.

    This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • files: string | readonly string[] | {
          buffer: Buffer;
          mimeType: string;
          name: string;
      } | readonly {
          buffer: Buffer;
          mimeType: string;
          name: string;
      }[]
    • Optional options: {
          noWaitAfter?: boolean;
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<void>

  • NOTE Use locator-based locator.tap([options]) instead. Read more about locators.

    This method taps an element matching selector by performing the following steps:

    1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
    2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
    3. Scroll the element into view if needed.
    4. Use page.touchscreen to tap the center of the element, or the specified position.
    5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

    When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

    NOTE frame.tap() requires that the hasTouch option of the browser context be set to true.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          force?: boolean;
          modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[];
          noWaitAfter?: boolean;
          position?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]

        Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional position?: {
            x: number;
            y: number;
        }

        A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • NOTE Use locator-based locator.textContent([options]) instead. Read more about locators.

    Returns element.textContent.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<string>

  • Returns the page title.

    Returns Promise<string>

  • Sends a keydown, keypress/input, and keyup event for each character in the text. frame.type can be used to send fine-grained keyboard events. To fill values in form fields, use frame.fill(selector, value[, options]).

    To press a special key, like Control or ArrowDown, use keyboard.press(key[, options]).

    Usage

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • text: string

      A text to type into a focused element.

    • Optional options: {
          delay?: number;
          noWaitAfter?: boolean;
          strict?: boolean;
          timeout?: number;
      }
      Optional
      • Optional delay?: number

        Time to wait between key presses in milliseconds. Defaults to 0.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

    Returns Promise<void>

    Deprecated

    In most cases, you should use locator.fill(value[, options]) instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use locator.pressSequentially(text[, options]).

  • NOTE Use locator-based locator.uncheck([options]) instead. Read more about locators.

    This method checks an element matching selector by performing the following steps:

    1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
    2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
    3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
    4. Scroll the element into view if needed.
    5. Use page.mouse to click in the center of the element.
    6. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
    7. Ensure that the element is now unchecked. If not, this method throws.

    When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

    Parameters

    • selector: string

      A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.

    • Optional options: {
          force?: boolean;
          noWaitAfter?: boolean;
          position?: {
              x: number;
              y: number;
          };
          strict?: boolean;
          timeout?: number;
          trial?: boolean;
      }
      Optional
      • Optional force?: boolean

        Whether to bypass the actionability checks. Defaults to false.

      • Optional noWaitAfter?: boolean

        Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.

      • Optional position?: {
            x: number;
            y: number;
        }

        A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.

        • x: number
        • y: number
      • Optional strict?: boolean

        When true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.

      • Optional timeout?: number

        Maximum time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional trial?: boolean

        When set, this method only performs the actionability checks and skips the action. Defaults to false. Useful to wait until the element is ready for the action without performing it.

    Returns Promise<void>

  • Returns frame's url.

    Returns string

  • Returns when the pageFunction returns a truthy value, returns that value.

    Usage

    The frame.waitForFunction(pageFunction[, arg, options]) can be used to observe viewport size change:

    const { firefox } = require('playwright');  // Or 'chromium' or 'webkit'.

    (async () => {
    const browser = await firefox.launch();
    const page = await browser.newPage();
    const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
    await page.setViewportSize({ width: 50, height: 50 });
    await watchDog;
    await browser.close();
    })();

    To pass an argument to the predicate of frame.waitForFunction function:

    const selector = '.foo';
    await frame.waitForFunction(selector => !!document.querySelector(selector), selector);

    Type Parameters

    • R

    • Arg

    Parameters

    • pageFunction: PageFunction<Arg, R>

      Function to be evaluated in the page context.

    • arg: Arg

      Optional argument to pass to pageFunction.

    • Optional options: PageWaitForFunctionOptions
      Optional

    Returns Promise<SmartHandle<R>>

  • Returns when the pageFunction returns a truthy value, returns that value.

    Usage

    The frame.waitForFunction(pageFunction[, arg, options]) can be used to observe viewport size change:

    const { firefox } = require('playwright');  // Or 'chromium' or 'webkit'.

    (async () => {
    const browser = await firefox.launch();
    const page = await browser.newPage();
    const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
    await page.setViewportSize({ width: 50, height: 50 });
    await watchDog;
    await browser.close();
    })();

    To pass an argument to the predicate of frame.waitForFunction function:

    const selector = '.foo';
    await frame.waitForFunction(selector => !!document.querySelector(selector), selector);

    Type Parameters

    • R

    Parameters

    • pageFunction: PageFunction<void, R>

      Function to be evaluated in the page context.

    • Optional arg: any

      Optional argument to pass to pageFunction.

      Optional
    • Optional options: PageWaitForFunctionOptions
      Optional

    Returns Promise<SmartHandle<R>>

  • Waits for the required load state to be reached.

    This returns when the frame reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.

    NOTE Most of the time, this method is not needed because Playwright auto-waits before every action.

    Usage

    await frame.click('button'); // Click triggers navigation.
    await frame.waitForLoadState(); // Waits for 'load' state by default.

    Parameters

    • Optional state: "load" | "domcontentloaded" | "networkidle"

      Optional load state to wait for, defaults to load. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:

      • 'load' - wait for the load event to be fired.
      • 'domcontentloaded' - wait for the DOMContentLoaded event to be fired.
      • 'networkidle' - DISCOURAGED wait until there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      Optional
    • Optional options: {
          timeout?: number;
      }
      Optional

    Returns Promise<void>

  • Waits for the frame navigation and returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.

    Usage

    This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly cause the frame to navigate. Consider this example:

    // Start waiting for navigation before clicking. Note no await.
    const navigationPromise = page.waitForNavigation();
    await page.getByText('Navigate after timeout').click();
    await navigationPromise;

    NOTE Usage of the History API to change the URL is considered a navigation.

    Parameters

    • Optional options: {
          timeout?: number;
          url?: string | RegExp | ((url) => boolean);
          waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
      }
      Optional
      • Optional timeout?: number

        Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(timeout), browserContext.setDefaultTimeout(timeout), page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional url?: string | RegExp | ((url) => boolean)

        A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.

      • Optional waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit"

        When to consider operation succeeded, defaults to load. Events can be either:

        • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
        • 'load' - consider operation to be finished when the load event is fired.
        • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
        • 'commit' - consider operation to be finished when network response is received and the document started loading.

    Returns Promise<Response>

    Deprecated

    This method is inherently racy, please use frame.waitForURL(url[, options]) instead.

  • NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.

    Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

    NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.

    Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

    Usage

    This method works across navigations:

    const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

    (async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    for (const currentURL of ['https://google.com', 'https://bbc.com']) {
    await page.goto(currentURL);
    const element = await page.mainFrame().waitForSelector('img');
    console.log('Loaded image: ' + await element.getAttribute('src'));
    }
    await browser.close();
    })();

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    Parameters

    • selector: K

      A selector to query for.

    • Optional options: PageWaitForSelectorOptionsNotHidden
      Optional

    Returns Promise<ElementHandleForTag<K>>

  • NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.

    Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

    NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.

    Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

    Usage

    This method works across navigations:

    const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

    (async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    for (const currentURL of ['https://google.com', 'https://bbc.com']) {
    await page.goto(currentURL);
    const element = await page.mainFrame().waitForSelector('img');
    console.log('Loaded image: ' + await element.getAttribute('src'));
    }
    await browser.close();
    })();

    Parameters

    • selector: string

      A selector to query for.

    • Optional options: PageWaitForSelectorOptionsNotHidden
      Optional

    Returns Promise<ElementHandle<HTMLElement | SVGElement>>

  • NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.

    Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

    NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.

    Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

    Usage

    This method works across navigations:

    const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

    (async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    for (const currentURL of ['https://google.com', 'https://bbc.com']) {
    await page.goto(currentURL);
    const element = await page.mainFrame().waitForSelector('img');
    console.log('Loaded image: ' + await element.getAttribute('src'));
    }
    await browser.close();
    })();

    Type Parameters

    • K extends keyof HTMLElementTagNameMap

    Parameters

    • selector: K

      A selector to query for.

    • options: PageWaitForSelectorOptions

    Returns Promise<ElementHandleForTag<K>>

  • NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.

    Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

    NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.

    Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

    Usage

    This method works across navigations:

    const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

    (async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    for (const currentURL of ['https://google.com', 'https://bbc.com']) {
    await page.goto(currentURL);
    const element = await page.mainFrame().waitForSelector('img');
    console.log('Loaded image: ' + await element.getAttribute('src'));
    }
    await browser.close();
    })();

    Parameters

    • selector: string

      A selector to query for.

    • options: PageWaitForSelectorOptions

    Returns Promise<ElementHandle<HTMLElement | SVGElement>>

  • NOTE Never wait for timeout in production. Tests that wait for time are inherently flaky. Use Locator actions and web assertions that wait automatically.

    Waits for the given timeout in milliseconds.

    Note that frame.waitForTimeout() should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.

    Parameters

    • timeout: number

      A timeout to wait for

    Returns Promise<void>

  • Waits for the frame to navigate to the given URL.

    Usage

    await frame.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation
    await frame.waitForURL('**/target.html');

    Parameters

    • url: string | RegExp | ((url) => boolean)

      A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.

    • Optional options: {
          timeout?: number;
          waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
      }
      Optional
      • Optional timeout?: number

        Maximum operation time in milliseconds. Defaults to 0 - no timeout. The default value can be changed via navigationTimeout option in the config, or by using the browserContext.setDefaultNavigationTimeout(timeout), browserContext.setDefaultTimeout(timeout), page.setDefaultNavigationTimeout(timeout) or page.setDefaultTimeout(timeout) methods.

      • Optional waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit"

        When to consider operation succeeded, defaults to load. Events can be either:

        • 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired.
        • 'load' - consider operation to be finished when the load event is fired.
        • 'networkidle' - DISCOURAGED consider operation to be finished when there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
        • 'commit' - consider operation to be finished when network response is received and the document started loading.

    Returns Promise<void>

Generated using TypeDoc