Skip to main content

Page

Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.

This example creates a page, navigates it to a URL, and then saves a screenshot:

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

(async () => {
const browser = await webkit.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'screenshot.png' });
await browser.close();
})();

The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter methods, such as on, once or removeListener.

This example logs a message for a single page load event:

page.once('load', () => console.log('Page loaded!'));

To unsubscribe from events use the removeListener method:

function logRequest(interceptedRequest) {
console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
// Sometime later...
page.removeListener('request', logRequest);

Methods​

addInitScript​

Added before v1.9 page.addInitScript

Adds a script which would be evaluated in one of the following scenarios:

  • Whenever the page is navigated.
  • Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.

The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

Usage

An example of overriding Math.random before the page loads:

// preload.js
Math.random = () => 42;
// In your playwright script, assuming the preload.js file is in same directory
await page.addInitScript({ path: './preload.js' });
await page.addInitScript(mock => {
window.mock = mock;
}, mock);
note

The order of evaluation of multiple scripts installed via browserContext.addInitScript() and page.addInitScript() is not defined.

Arguments

  • script function | string | Object#

    • path string (optional)

      Path to the JavaScript file. If path is a relative path, then it is resolved relative to the current working directory. Optional.

    • content string (optional)

      Raw script content. Optional.

    Script to be evaluated in the page.

  • arg Serializable (optional)#

    Optional argument to pass to script (only supported when passing a function).

  • options Object (optional)

    • exposeFunctions boolean (optional) Added in: v1.62#

      When set to true, functions passed inside arg are exposed in the page and can be called from the init script. Calling one returns a Promise of its result. Under the hood, each function is exposed via page.exposeFunction(), so it is technically accessible from all frames of the page. Unlike functions passed to page.evaluate(), functions passed to an init script are exposed in every new document, so they survive navigations. Defaults to false, in which case functions are not serializable and are silently dropped.

Returns


addLocatorHandler​

Added in: v1.42 page.addLocatorHandler

When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.

This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.

Things to keep in mind:

  • When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of your normal test flow, instead of using page.addLocatorHandler().
  • Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
  • After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You can opt-out of this behavior with noWaitAfter.
  • The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
  • You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.
warning

Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.

For example, consider a test that calls locator.focus() followed by keyboard.press(). If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use locator.press() instead to avoid this problem.

Another example is a series of mouse actions, where mouse.move() is followed by mouse.down(). Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions like locator.click() that do not rely on the state being unchanged by a handler.

Usage

An example that closes a "Sign up to the newsletter" dialog when it appears:

// Setup the handler.
await page.addLocatorHandler(page.getByText('Sign up to the newsletter'), async () => {
await page.getByRole('button', { name: 'No thanks' }).click();
});

// Write the test as usual.
await page.goto('https://example.com');
await page.getByRole('button', { name: 'Start here' }).click();

An example that skips the "Confirm your security details" page when it is shown:

// Setup the handler.
await page.addLocatorHandler(page.getByText('Confirm your security details'), async () => {
await page.getByRole('button', { name: 'Remind me later' }).click();
});

// Write the test as usual.
await page.goto('https://example.com');
await page.getByRole('button', { name: 'Start here' }).click();

An example with a custom callback on every actionability check. It uses a <body> locator that is always visible, so the handler is called before every actionability check. It is important to specify noWaitAfter, because the handler does not hide the <body> element.

// Setup the handler.
await page.addLocatorHandler(page.locator('body'), async () => {
await page.evaluate(() => window.removeObstructionsForTestIfNeeded());
}, { noWaitAfter: true });

// Write the test as usual.
await page.goto('https://example.com');
await page.getByRole('button', { name: 'Start here' }).click();

Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting times:

await page.addLocatorHandler(page.getByLabel('Close'), async locator => {
await locator.click();
}, { times: 1 });

Arguments

  • locator Locator#

    Locator that triggers the handler.

  • handler function(Locator):Promise<Object>#

    Function that should be run once locator appears. This function should get rid of the element that blocks actions like click.

  • options Object (optional)

    • noWaitAfter boolean (optional) Added in: v1.44#

      By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.

    • times number (optional) Added in: v1.44#

      Specifies the maximum number of times this handler should be called. Unlimited by default.

Returns


addScriptTag​

Added before v1.9 page.addScriptTag

Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.

Usage

await page.addScriptTag();
await page.addScriptTag(options);

Arguments

  • options Object (optional)
    • content string (optional)#

      Raw JavaScript content to be injected into frame.

    • path string (optional)#

      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.

    • type string (optional)#

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

    • url string (optional)#

      URL of a script to be added.

Returns


addStyleTag​

Added before v1.9 page.addStyleTag

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.

Usage

await page.addStyleTag();
await page.addStyleTag(options);

Arguments

  • options Object (optional)
    • content string (optional)#

      Raw CSS content to be injected into frame.

    • path string (optional)#

      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.

    • url string (optional)#

      URL of the <link> tag.

Returns


ariaSnapshot​

Added in: v1.59 page.ariaSnapshot

Captures the aria snapshot of the page. Read more about aria snapshots.

Usage

await page.ariaSnapshot();
await page.ariaSnapshot(options);

Arguments

  • options Object (optional)
    • boxes boolean (optional) Added in: v1.60#

      When true, appends each element's bounding box as [box=x,y,width,height] to the snapshot. Coordinates are relative to the viewport, in CSS pixels, as returned by Element.getBoundingClientRect(). Defaults to false.

    • depth number (optional)#

      When specified, limits the depth of the snapshot.

    • mode "ai" | "default" (optional)#

      When set to "ai", returns a snapshot optimized for AI consumption: including element references like [ref=e2] and snapshots of <iframe>s. Defaults to "default".

    • signal AbortSignal (optional) Added in: v1.62#

      Allows to cancel the operation using an AbortSignal. If the signal is aborted, the operation will be aborted and throw an error. Note that providing a signal does not disable the default timeout, which can be changed using browserContext.setDefaultTimeout() or page.setDefaultTimeout(); pass timeout: 0 to disable the timeout entirely.

    • timeout number (optional)#

      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() or page.setDefaultTimeout() methods.

Returns


ariaSnapshotJSON​

Added in: v1.63 page.ariaSnapshotJSON

Captures the aria snapshot of the page as a free form JSON object. Returns the same tree as page.ariaSnapshot(), serialized as a JSON value instead of YAML markup. See locator.ariaSnapshotJSON() for the details of the format.

Usage

await page.ariaSnapshotJSON();
await page.ariaSnapshotJSON(options);

Arguments

  • options Object (optional)
    • boxes boolean (optional)#

      When true, includes each element's bounding box as a box property with x, y, width and height. Coordinates are relative to the viewport, in CSS pixels, as returned by Element.getBoundingClientRect(). Defaults to false.

    • depth number (optional)#

      When specified, limits the depth of the snapshot.

    • mode "ai" | "default" (optional)#

      When set to "ai", returns a snapshot optimized for AI consumption: including element references like [ref=e2] and snapshots of <iframe>s. Defaults to "default".

    • signal AbortSignal (optional) Added in: v1.62#

      Allows to cancel the operation using an AbortSignal. If the signal is aborted, the operation will be aborted and throw an error. Note that providing a signal does not disable the default timeout, which can be changed using browserContext.setDefaultTimeout() or page.setDefaultTimeout(); pass timeout: 0 to disable the timeout entirely.

    • timeout number (optional)#

      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() or page.setDefaultTimeout() methods.

Returns


bringToFront​

Added before v1.9 page.bringToFront

Brings page to front (activates tab).

Usage

await page.bringToFront();

Returns


cancelPickLocator​

Added in: v1.59 page.cancelPickLocator

Cancels an ongoing page.pickLocator() call by deactivating pick locator mode. If no pick locator mode is active, this method is a no-op.

Usage

await page.cancelPickLocator();

Returns


clearConsoleMessages​

Added in: v1.59 page.clearConsoleMessages

Clears all stored console messages from this page. Subsequent calls to page.consoleMessages() will only return messages logged after the clear.

Usage

await page.clearConsoleMessages();

Returns


clearPageErrors​

Added in: v1.59 page.clearPageErrors

Clears all stored page errors from this page. Subsequent calls to page.pageErrors() will only return errors thrown after the clear.

Usage

await page.clearPageErrors();

Returns


close​

Added before v1.9 page.close

If runBeforeUnload is false, does not run any unload handlers and waits for the page to be closed. If runBeforeUnload is true the method will run unload handlers, but will not wait for the page to close.

By default, page.close() does not run beforeunload handlers.

note

if runBeforeUnload is passed as true, a beforeunload dialog might be summoned and should be handled manually via page.on('dialog') event.

Usage

await page.close();
await page.close(options);

Arguments

  • options Object (optional)
    • reason string (optional) Added in: v1.40#

      The reason to be reported to the operations interrupted by the page closure.

    • runBeforeUnload boolean (optional)#

      Defaults to false. Whether to run the before unload page handlers.

Returns


consoleMessages​

Added in: v1.56 page.consoleMessages

Returns up to (currently) 200 last console messages from this page. See page.on('console') for more details.

Usage

await page.consoleMessages();
await page.consoleMessages(options);

Arguments

  • options Object (optional)
    • filter "all" | "since-navigation" (optional) Added in: v1.59#

      Controls which messages are returned:

Returns


content​

Added before v1.9 page.content

Gets the full HTML contents of the page, including the doctype.

Usage

await page.content();
await page.content(options);

Arguments

  • options Object (optional)
    • includeShadow boolean (optional) Added in: v1.64#

      When true, contents of open shadow roots are included as declarative shadow DOM, i.e. <template shadowrootmode="open"> elements nested inside their host elements. Closed shadow roots are never included. Defaults to false.

Returns


context​

Added before v1.9 page.context

Get the browser context that the page belongs to.

Usage

page.context();

Returns


dragAndDrop​

Added in: v1.13 page.dragAndDrop

This method drags the source element to the target element. It will first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.

Usage

await page.dragAndDrop('#source', '#target');
// or specify exact positions relative to the top-left corners of the elements:
await page.dragAndDrop('#source', '#target', {
sourcePosition: { x: 34, y: 7 },
targetPosition: { x: 10, y: 20 },
});

Arguments

  • 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.

  • options Object (optional)

    • force boolean (optional)#

      Whether to bypass the actionability checks. Defaults to false.

    • noWaitAfter boolean (optional)#

      Deprecated

      This option has no effect.

      This option has no effect.

    • scroll "auto" | "none" (optional) Added in: v1.62#

      Controls whether Playwright scrolls the element into view before performing the action. Defaults to "auto", which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to "none", Playwright does not scroll the element and the action fails if the element is not already in the viewport. This is useful to assert that an element is reachable by the user without additional scrolling.

    • signal AbortSignal (optional) Added in: v1.62#

      Allows to cancel the operation using an AbortSignal. If the signal is aborted, the operation will be aborted and throw an error. Note that providing a signal does not disable the default timeout, which can be changed using browserContext.setDefaultTimeout() or page.setDefaultTimeout(); pass timeout: 0 to disable the timeout entirely.

    • sourcePosition Object (optional) Added in: v1.14#

      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.

    • steps number (optional) Added in: v1.57#

      Defaults to 1. Sends n interpolated mousemove events to represent travel between the mousedown and mouseup of the drag. When set to 1, emits a single mousemove event at the destination location.

    • strict boolean (optional) Added in: v1.14#

      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.

    • targetPosition Object (optional) Added in: v1.14#

      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.

    • timeout number (optional)#

      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() or page.setDefaultTimeout() methods.

    • trial boolean (optional)#

      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


emulateMedia​

Added before v1.9 page.emulateMedia

This method changes the CSS media type through the media argument, and/or the 'prefers-colors-scheme' media feature, using the colorScheme argument.

Usage

await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false

await page.emulateMedia({ media: 'print' });
await page.evaluate(() => matchMedia('screen').matches);
// → false
await page.evaluate(() => matchMedia('print').matches);
// → true

await page.emulateMedia({});
await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false
await page.emulateMedia({ colorScheme: 'dark' });
await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
// → true
await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
// → false

Arguments

  • options Object (optional)
    • colorScheme null | "light" | "dark" | "no-preference" (optional) Added in: v1.9#

      Emulates prefers-colors-scheme media feature, supported values are 'light' and 'dark'. Passing null disables color scheme emulation. 'no-preference' is deprecated.

    • contrast null | "no-preference" | "more" (optional) Added in: v1.51#

      Emulates 'prefers-contrast' media feature, supported values are 'no-preference', 'more'. Passing null disables contrast emulation.

    • forcedColors null | "active" | "none" (optional) Added in: v1.15#

      Emulates 'forced-colors' media feature, supported values are 'active' and 'none'. Passing null disables forced colors emulation.

    • media null | "screen" | "print" (optional) Added in: v1.9#

      Changes the CSS media type of the page. The only allowed values are 'screen', 'print' and null. Passing null disables CSS media emulation.

    • reducedMotion null | "reduce" | "no-preference" (optional) Added in: v1.12#

      Emulates 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. Passing null disables reduced motion emulation.

Returns


evaluate​

Added before v1.9 page.evaluate

Returns the value of the pageFunction invocation.

If the function passed to the page.evaluate() returns a Promise, then page.evaluate() would wait for the promise to resolve and return its value.

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

Usage

Passing argument to pageFunction:

const result = await page.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 page.evaluate('1 + 2')); // prints "3"
const x = 10;
console.log(await page.evaluate(`1 + ${x}`)); // prints "11"

ElementHandle instances can be passed as an argument to the page.evaluate():

const bodyHandle = await page.evaluateHandle('document.body');
const html = await page.evaluate<string, HTMLElement>(([body, suffix]) =>
body.innerHTML + suffix, [bodyHandle, 'hello']
);
await bodyHandle.dispose();

Arguments