# class: 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); ``` ## event: Page.close Emitted when the page closes. ## event: Page.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'})); ``` ## event: Page.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)); }); ``` ## event: Page.dialog - type: <[Dialog]> Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond to the dialog via [`method: Dialog.accept`] or [`method: Dialog.dismiss`] methods. ## event: Page.domcontentloaded Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched. ## event: Page.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. ## event: Page.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 [`method: FileChooser.setFiles`] that can be uploaded after that. ```js page.on('filechooser', async (fileChooser) => { await fileChooser.setFiles('/tmp/myfile.pdf'); }); ``` ## event: Page.frameattached - type: <[Frame]> Emitted when a frame is attached. ## event: Page.framedetached - type: <[Frame]> Emitted when a frame is detached. ## event: Page.framenavigated - type: <[Frame]> Emitted when a frame is navigated to a new url. ## event: Page.load Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. ## event: Page.pageerror - type: <[Error]> Emitted when an uncaught exception happens within the page. ## event: Page.popup - type: <[Page]> Emitted when the page opens a new tab or window. This event is emitted in addition to the [`event: BrowserContext.page`], 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 [`method: Page.waitForLoadState`] to wait until the page gets to a particular state (you should not need it in most cases). ## event: Page.request - type: <[Request]> Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see [`method: Page.route`] or [`method: BrowserContext.route`]. ## event: Page.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 [`event: Page.requestfinished`] event and not with [`event: Page.requestfailed`]. ## event: Page.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`. ## event: Page.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`. ## event: Page.websocket - type: <[WebSocket]> Emitted when <[WebSocket]> request is sent. ## event: Page.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. ## async method: Page.$ * langs: - alias-python: query_selector - returns: <[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 [`method: Frame.$`]. ### param: Page.$.selector = %%-query-selector-%% ## async method: Page.$$ * langs: - alias-python: query_selector_all - returns: <[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 [`method: Frame.$$`]. ### param: Page.$$.selector = %%-query-selector-%% ## async method: Page.$eval * langs: - alias-python: eval_on_selector - returns: <[Serializable]> The method finds an element matching the specified selector within the page and passes it as a first argument to [`param: pageFunction`]. If no elements match the selector, the method throws an error. Returns the value of [`param: pageFunction`]. If [`param: pageFunction`] returns a [Promise], then [`method: Page.$eval`] 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 [`method: Frame.$eval`]. ### param: Page.$eval.selector = %%-query-selector-%% ### param: Page.$eval.pageFunction * langs: js - `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context ### param: Page.$eval.arg - `arg` <[EvaluationArgument]> Optional argument to pass to [`param: pageFunction`] ## async method: Page.$$eval * langs: - alias-python: eval_on_selector_all - returns: <[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 [`param: pageFunction`]. Returns the result of [`param: pageFunction`] invocation. If [`param: pageFunction`] returns a [Promise], then [`method: Page.$$eval`] 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); ``` ### param: Page.$$eval.selector = %%-query-selector-%% ### param: Page.$$eval.pageFunction * langs: js - `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context ### param: Page.$$eval.arg - `arg` <[EvaluationArgument]> Optional argument to pass to [`param: pageFunction`] ## property: Page.accessibility - type: <[Accessibility]> ## async method: 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`. 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 [`method: BrowserContext.addInitScript`] and [`method: Page.addInitScript`] is not defined. ### param: Page.addInitScript.script * langs: js - `script` <[function]|[string]|[Object]> - `path` <[path]> 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. Script to be evaluated in the page. ### param: Page.addInitScript.arg * langs: js - `arg` <[Serializable]> Optional argument to pass to [`param: script`] (only supported when passing a function). ## async method: Page.addScriptTag - returns: <[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(`