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

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


`);
await page.click('button');
})();

Arguments

  • name string#

    Name of the function on the window object.

  • callback function#

    Callback function that will be called in the Playwright's context.

  • options Object (optional)

    • handle boolean (optional)#

      Deprecated

      This option will be removed in the future.

      Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.

Returns


exposeFunction

Added before v1.9 page.exposeFunction

The method adds a function called name on the window object of every frame in the page. When called, the function executes callback and returns a Promise which resolves to the return value of callback.

If the callback returns a Promise, it will be awaited.

See browserContext.exposeFunction() for context-wide exposed function.

note

Functions installed via page.exposeFunction() survive navigations.

Usage

An example of adding a sha256 function to the page:

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

(async () => {
const browser = await webkit.launch({ headless: false });
const page = await browser.newPage();
await page.exposeFunction('sha256', text =>
crypto.createHash('sha256').update(text).digest('hex'),
);
await page.setContent(`



`);
await page.click('button');
})();

Arguments

  • name string#

    Name of the function on the window object

  • callback function#

    Callback function which will be called in Playwright's context.

Returns


frame

Added before v1.9 page.frame

Returns frame matching the specified criteria. Either name or url must be specified.

Usage

const frame = page.frame('frame-name');
const frame = page.frame({ url: /.*domain.*/ });

Arguments

  • frameSelector string | Object#

    • name string (optional)

      Frame name specified in the iframe's name attribute. Optional.

    • url string | RegExp | function(URL):boolean (optional)

      A glob pattern, regex pattern or predicate receiving frame's url as a URL object. Optional.

    Frame name or other frame lookup options.

Returns


frameLocator

Added in: v1.17 page.frameLocator

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