--- id: class-page title: "Page" --- * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) Page provides methods to interact with a single tab in a [Browser], or an [extension background page](https://developer.chrome.com/extensions/background_pages) 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: ```js 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`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or `removeListener`. This example logs a message for a single page `load` event: ```js page.once('load', () => console.log('Page loaded!')); ``` To unsubscribe from events use the `removeListener` method: ```js function logRequest(interceptedRequest) { console.log('A request was made:', interceptedRequest.url()); } page.on('request', logRequest); // Sometime later... page.removeListener('request', logRequest); ``` - [page.on('close')](api/class-page.md#pageonclose) - [page.on('console')](api/class-page.md#pageonconsole) - [page.on('crash')](api/class-page.md#pageoncrash) - [page.on('dialog')](api/class-page.md#pageondialog) - [page.on('domcontentloaded')](api/class-page.md#pageondomcontentloaded) - [page.on('download')](api/class-page.md#pageondownload) - [page.on('filechooser')](api/class-page.md#pageonfilechooser) - [page.on('frameattached')](api/class-page.md#pageonframeattached) - [page.on('framedetached')](api/class-page.md#pageonframedetached) - [page.on('framenavigated')](api/class-page.md#pageonframenavigated) - [page.on('load')](api/class-page.md#pageonload) - [page.on('pageerror')](api/class-page.md#pageonpageerror) - [page.on('popup')](api/class-page.md#pageonpopup) - [page.on('request')](api/class-page.md#pageonrequest) - [page.on('requestfailed')](api/class-page.md#pageonrequestfailed) - [page.on('requestfinished')](api/class-page.md#pageonrequestfinished) - [page.on('response')](api/class-page.md#pageonresponse) - [page.on('websocket')](api/class-page.md#pageonwebsocket) - [page.on('worker')](api/class-page.md#pageonworker) - [page.$(selector)](api/class-page.md#pageselector) - [page.$$(selector)](api/class-page.md#pageselector-1) - [page.$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg) - [page.$$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg-1) - [page.accessibility](api/class-page.md#pageaccessibility) - [page.addInitScript(script[, arg])](api/class-page.md#pageaddinitscriptscript-arg) - [page.addScriptTag(params)](api/class-page.md#pageaddscripttagparams) - [page.addStyleTag(params)](api/class-page.md#pageaddstyletagparams) - [page.bringToFront()](api/class-page.md#pagebringtofront) - [page.check(selector[, options])](api/class-page.md#pagecheckselector-options) - [page.click(selector[, options])](api/class-page.md#pageclickselector-options) - [page.close([options])](api/class-page.md#pagecloseoptions) - [page.content()](api/class-page.md#pagecontent) - [page.context()](api/class-page.md#pagecontext) - [page.coverage](api/class-page.md#pagecoverage) - [page.dblclick(selector[, options])](api/class-page.md#pagedblclickselector-options) - [page.dispatchEvent(selector, type[, eventInit, options])](api/class-page.md#pagedispatcheventselector-type-eventinit-options) - [page.emulateMedia(params)](api/class-page.md#pageemulatemediaparams) - [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg) - [page.evaluateHandle(pageFunction[, arg])](api/class-page.md#pageevaluatehandlepagefunction-arg) - [page.exposeBinding(name, callback[, options])](api/class-page.md#pageexposebindingname-callback-options) - [page.exposeFunction(name, callback)](api/class-page.md#pageexposefunctionname-callback) - [page.fill(selector, value[, options])](api/class-page.md#pagefillselector-value-options) - [page.focus(selector[, options])](api/class-page.md#pagefocusselector-options) - [page.frame(frameSelector)](api/class-page.md#pageframeframeselector) - [page.frames()](api/class-page.md#pageframes) - [page.getAttribute(selector, name[, options])](api/class-page.md#pagegetattributeselector-name-options) - [page.goBack([options])](api/class-page.md#pagegobackoptions) - [page.goForward([options])](api/class-page.md#pagegoforwardoptions) - [page.goto(url[, options])](api/class-page.md#pagegotourl-options) - [page.hover(selector[, options])](api/class-page.md#pagehoverselector-options) - [page.innerHTML(selector[, options])](api/class-page.md#pageinnerhtmlselector-options) - [page.innerText(selector[, options])](api/class-page.md#pageinnertextselector-options) - [page.isClosed()](api/class-page.md#pageisclosed) - [page.keyboard](api/class-page.md#pagekeyboard) - [page.mainFrame()](api/class-page.md#pagemainframe) - [page.mouse](api/class-page.md#pagemouse) - [page.opener()](api/class-page.md#pageopener) - [page.pdf([options])](api/class-page.md#pagepdfoptions) - [page.press(selector, key[, options])](api/class-page.md#pagepressselector-key-options) - [page.reload([options])](api/class-page.md#pagereloadoptions) - [page.route(url, handler)](api/class-page.md#pagerouteurl-handler) - [page.screenshot([options])](api/class-page.md#pagescreenshotoptions) - [page.selectOption(selector, values[, options])](api/class-page.md#pageselectoptionselector-values-options) - [page.setContent(html[, options])](api/class-page.md#pagesetcontenthtml-options) - [page.setDefaultNavigationTimeout(timeout)](api/class-page.md#pagesetdefaultnavigationtimeouttimeout) - [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) - [page.setExtraHTTPHeaders(headers)](api/class-page.md#pagesetextrahttpheadersheaders) - [page.setInputFiles(selector, files[, options])](api/class-page.md#pagesetinputfilesselector-files-options) - [page.setViewportSize(viewportSize)](api/class-page.md#pagesetviewportsizeviewportsize) - [page.tap(selector[, options])](api/class-page.md#pagetapselector-options) - [page.textContent(selector[, options])](api/class-page.md#pagetextcontentselector-options) - [page.title()](api/class-page.md#pagetitle) - [page.touchscreen](api/class-page.md#pagetouchscreen) - [page.type(selector, text[, options])](api/class-page.md#pagetypeselector-text-options) - [page.uncheck(selector[, options])](api/class-page.md#pageuncheckselector-options) - [page.unroute(url[, handler])](api/class-page.md#pageunrouteurl-handler) - [page.url()](api/class-page.md#pageurl) - [page.video()](api/class-page.md#pagevideo) - [page.viewportSize()](api/class-page.md#pageviewportsize) - [page.waitForEvent(event[, optionsOrPredicate])](api/class-page.md#pagewaitforeventevent-optionsorpredicate) - [page.waitForFunction(pageFunction[, arg, options])](api/class-page.md#pagewaitforfunctionpagefunction-arg-options) - [page.waitForLoadState([state, options])](api/class-page.md#pagewaitforloadstatestate-options) - [page.waitForNavigation([options])](api/class-page.md#pagewaitfornavigationoptions) - [page.waitForRequest(urlOrPredicate[, options])](api/class-page.md#pagewaitforrequesturlorpredicate-options) - [page.waitForResponse(urlOrPredicate[, options])](api/class-page.md#pagewaitforresponseurlorpredicate-options) - [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options) - [page.waitForTimeout(timeout)](api/class-page.md#pagewaitfortimeouttimeout) - [page.workers()](api/class-page.md#pageworkers) ## page.on('close') Emitted when the page closes. ## page.on('console') - type: <[ConsoleMessage]> Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also emitted if the page throws an error or a warning. The arguments passed into `console.log` appear as arguments on the event handler. An example of handling `console` event: ```js page.on('console', msg => { for (let i = 0; i < msg.args().length; ++i) console.log(`${i}: ${msg.args()[i]}`); }); page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); ``` ## page.on('crash') Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw. The most common way to deal with crashes is to catch an exception: ```js try { // Crash might happen during a click. await page.click('button'); // Or while waiting for an event. await page.waitForEvent('popup'); } catch (e) { // When the page crashes, exception message contains 'crash'. } ``` However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, handling `crash` event helps: ```js await new Promise((resolve, reject) => { page.on('requestfinished', async request => { if (await someProcessing(request)) resolve(request); }); page.on('crash', error => reject(error)); }); ``` ## page.on('dialog') - type: <[Dialog]> Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond to the dialog via [dialog.accept([promptText])](api/class-dialog.md#dialogacceptprompttext) or [dialog.dismiss()](api/class-dialog.md#dialogdismiss) methods. ## page.on('domcontentloaded') Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched. ## page.on('download') - type: <[Download]> Emitted when attachment download started. User can access basic file operations on downloaded content via the passed [Download] instance. > **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual download is not performed and user has no access to the downloaded files. ## page.on('filechooser') - type: <[FileChooser]> Emitted when a file chooser is supposed to appear, such as after clicking the ``. Playwright can respond to it via setting the input files using [fileChooser.setFiles(files[, options])](api/class-filechooser.md#filechoosersetfilesfiles-options) that can be uploaded after that. ```js page.on('filechooser', async (fileChooser) => { await fileChooser.setFiles('/tmp/myfile.pdf'); }); ``` ## page.on('frameattached') - type: <[Frame]> Emitted when a frame is attached. ## page.on('framedetached') - type: <[Frame]> Emitted when a frame is detached. ## page.on('framenavigated') - type: <[Frame]> Emitted when a frame is navigated to a new url. ## page.on('load') Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. ## page.on('pageerror') - type: <[Error]> Emitted when an uncaught exception happens within the page. ## page.on('popup') - type: <[Page]> Emitted when the page opens a new tab or window. This event is emitted in addition to the [browserContext.on('page')](api/class-browsercontext.md#browsercontextonpage), but only for popups relevant to this page. The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup. ```js const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => window.open('https://example.com')), ]); console.log(await popup.evaluate('location.href')); ``` > **NOTE** Use [page.waitForLoadState([state, options])](api/class-page.md#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases). ## page.on('request') - type: <[Request]> Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see [page.route(url, handler)](api/class-page.md#pagerouteurl-handler) or [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler). ## page.on('requestfailed') - type: <[Request]> Emitted when a request fails, for example by timing out. > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with [page.on('requestfinished')](api/class-page.md#pageonrequestfinished) event and not with [page.on('requestfailed')](api/class-page.md#pageonrequestfailed). ## page.on('requestfinished') - type: <[Request]> Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is `request`, `response` and `requestfinished`. ## page.on('response') - type: <[Response]> Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events is `request`, `response` and `requestfinished`. ## page.on('websocket') - type: <[WebSocket]> Emitted when <[WebSocket]> request is sent. ## page.on('worker') - type: <[Worker]> Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the page. ## page.$(selector) - `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details. - returns: <[Promise]<[null]|[ElementHandle]>> The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to `null`. Shortcut for main frame's [frame.$(selector)](api/class-frame.md#frameselector). ## page.$$(selector) - `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details. - returns: <[Promise]<[Array]<[ElementHandle]>>> The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to `[]`. Shortcut for main frame's [frame.$$(selector)](api/class-frame.md#frameselector-1). ## page.$eval(selector, pageFunction[, arg]) - `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details. - `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction` - returns: <[Promise]<[Serializable]>> The method finds an element matching the specified selector within the page and passes it as a first argument to `pageFunction`. If no elements match the selector, the method throws an error. Returns the value of `pageFunction`. If `pageFunction` returns a [Promise], then [page.$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg) would wait for the promise to resolve and return its value. Examples: ```js const searchValue = await page.$eval('#search', el => el.value); const preloadHref = await page.$eval('link[rel=preload]', el => el.href); const html = await page.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello'); ``` Shortcut for main frame's [frame.$eval(selector, pageFunction[, arg])](api/class-frame.md#frameevalselector-pagefunction-arg). ## page.$$eval(selector, pageFunction[, arg]) - `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details. - `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction` - returns: <[Promise]<[Serializable]>> The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to `pageFunction`. Returns the result of `pageFunction` invocation. If `pageFunction` returns a [Promise], then [page.$$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg-1) would wait for the promise to resolve and return its value. Examples: ```js const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); ``` ## page.accessibility - type: <[Accessibility]> ## page.addInitScript(script[, arg]) - `script` <[function]|[string]|[Object]> Script to be evaluated in the page. - `path` <[string]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional. - `content` <[string]> Raw script content. Optional. - `arg` <[Serializable]> Optional argument to pass to `script` (only supported when passing a function). - returns: <[Promise]> 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`. An example of overriding `Math.random` before the page loads: ```js // preload.js Math.random = () => 42; // In your playwright script, assuming the preload.js file is in same directory const preloadFile = fs.readFileSync('./preload.js', 'utf8'); await page.addInitScript(preloadFile); ``` > **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](api/class-browsercontext.md#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](api/class-page.md#pageaddinitscriptscript-arg) is not defined. ## page.addScriptTag(params) - `params` <[Object]> - `url` <[string]> URL of a script to be added. 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. - `content` <[string]> Raw JavaScript content to be injected into frame. Optional. - `type` <[string]> Script type. Use 'module' in order to load a Javascript ES6 module. See [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details. Optional. - returns: <[Promise]<[ElementHandle]>> Adds a `
`); await page.click('button'); })(); ``` An example of passing an element handle: ```js await page.exposeBinding('clicked', async (source, element) => { console.log(await element.textContent()); }, { handle: true }); await page.setContent(`
Click me
Or click me
`); ``` ## page.exposeFunction(name, callback) - `name` <[string]> Name of the function on the window object - `callback` <[function]> Callback function which will be called in Playwright's context. - returns: <[Promise]> 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(name, callback)](api/class-browsercontext.md#browsercontextexposefunctionname-callback) for context-wide exposed function. > **NOTE** Functions installed via `page.exposeFunction` survive navigations. An example of adding an `md5` function to the page: ```js 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('md5', text => crypto.createHash('md5').update(text).digest('hex')); await page.setContent(`
`); await page.click('button'); })(); ``` An example of adding a `window.readfile` function to the page: ```js const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'. const fs = require('fs'); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); page.on('console', msg => console.log(msg.text())); await page.exposeFunction('readfile', async filePath => { return new Promise((resolve, reject) => { fs.readFile(filePath, 'utf8', (err, text) => { if (err) reject(err); else resolve(text); }); }); }); await page.evaluate(async () => { // use window.readfile to read contents of a file const content = await window.readfile('/etc/hosts'); console.log(content); }); await browser.close(); })(); ``` ## page.fill(selector, value[, options]) - `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details. - `value` <[string]> Value to fill for the ``, `