Page
- extends: EventEmitter
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 in: v1.8Adds 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);
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).
addScriptTag
Added in: v1.8Adds 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)-
Raw JavaScript content to be injected into frame.
-
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. -
Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.
-
URL of a script to be added.
-
Returns
addStyleTag
Added in: v1.8Adds 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)
Returns
bringToFront
Added in: v1.8Brings page to front (activates tab).
Usage
await page.bringToFront();
close
Added in: v1.8If 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.
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.
-
content
Added in: v1.8Gets the full HTML contents of the page, including the doctype.
Usage
await page.content();
Returns
context
Added in: v1.8Get the browser context that the page belongs to.
Usage
page.context();
Returns
dragAndDrop
Added in: v1.13This 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
-
A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
-
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)-
Whether to bypass the actionability checks. Defaults to
false
. -
noWaitAfter
boolean (optional)#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
. -
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.
-
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.
-
Maximum time in milliseconds. Defaults to
0
- no timeout. The default value can be changed viaactionTimeout
option in the config, or by using the browserContext.setDefaultTimeout() or page.setDefaultTimeout() methods. -
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.
-
emulateMedia
Added in: v1.8This 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
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').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'
,'dark'
,'no-preference'
. Passingnull
disables color scheme emulation. -
forcedColors
null|"active"|"none" (optional) Added in: v1.15#Emulates
'forced-colors'
media feature, supported values are'active'
and'none'
. Passingnull
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'
andnull
. Passingnull
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'
. Passingnull
disables reduced motion emulation.
-
evaluate
Added in: v1.8Returns 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.evaluate('document.body');
const html = await page.evaluate<string, HTMLElement>(([body, suffix]) =>
body.innerHTML + suffix, [bodyHandle, 'hello']
);
await bodyHandle.dispose();
Arguments
-
Function to be evaluated in the page context.
-
arg
EvaluationArgument (optional)#Optional argument to pass to
pageFunction
.
Returns
evaluateHandle
Added in: v1.8Returns the value of the pageFunction
invocation as a JSHandle.
The only difference between page.evaluate() and page.evaluateHandle() is that page.evaluateHandle() returns JSHandle.
If the function passed to the page.evaluateHandle() returns a Promise, then page.evaluateHandle() would wait for the promise to resolve and return its value.
Usage
// Handle for the window object.
const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window));
A string can also be passed in instead of a function:
const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'
JSHandle instances can be passed as an argument to the page.evaluateHandle():
const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
Arguments
-
Function to be evaluated in the page context.
-
arg
EvaluationArgument (optional)#Optional argument to pass to
pageFunction
.
Returns
exposeBinding
Added in: v1.8The method adds a function called name
on the window
object of every frame in this 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.
The first argument of the callback
function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }
.
See browserContext.exposeBinding() for the context-wide version.
Functions installed via page.exposeBinding() survive navigations.
Usage
An example of exposing page URL to all frames in a page:
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
(async () => {
const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.exposeBinding('pageURL', ({ page }) => page.url());
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})();
An example of passing an element handle:
await page.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
}, { handle: true });
await page.setContent(`
<script>
document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>
`);
Arguments
-
Name of the function on the window object.
-
Callback function that will be called in the Playwright's context.
-
options
Object (optional)
exposeFunction
Added in: v1.8The 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.
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(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})();
Arguments
-
Name of the function on the window object
-
Callback function which will be called in Playwright's context.
frame
Added in: v1.8Returns 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
Returns