# class: Page * extends: [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(); })(); ``` ```python async import asyncio from playwright.async_api import async_playwright async def run(playwright): webkit = playwright.webkit browser = await webkit.launch() context = await browser.new_context() page = await context.new_page() await page.goto("https://example.com") await page.screenshot(path="screenshot.png") await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` ```python sync from playwright.sync_api import sync_playwright def run(playwright): webkit = playwright.webkit browser = webkit.launch() context = browser.new_context() page = context.new_page() page.goto("https://example.com") page.screenshot(path="screenshot.png") browser.close() with sync_playwright() as playwright: run(playwright) ``` 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!')); ``` ```py page.once("load", lambda: print("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); ``` ```py def log_request(intercepted_request): print("a request was made:", intercepted_request.url) page.on("request", log_request) # sometime later... page.remove_listener("request", log_request) ``` ## event: Page.close - type: <[Page]> 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}: ${await msg.args()[i].jsonValue()}`); }); page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); ``` ```python async async def print_args(msg): for arg in msg.args: print(await arg.json_value()) page.on("console", print_args) await page.evaluate("console.log('hello', 5, {foo: 'bar'})") ``` ```python sync def print_args(msg): for arg in msg.args: print(arg.json_value()) page.on("console", print_args) page.evaluate("console.log('hello', 5, {foo: 'bar'})") ``` ## event: Page.crash - type: <[Page]> 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'. } ``` ```python async try: # crash might happen during a click. await page.click("button") # or while waiting for an event. await page.wait_for_event("popup") except Error as e: # when the page crashes, exception message contains "crash". ``` ```python sync try: # crash might happen during a click. page.click("button") # or while waiting for an event. page.wait_for_event("popup") except Error as e: # when the page crashes, exception message contains "crash". ``` ## event: Page.dialog - type: <[Dialog]> Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must** either [`method: Dialog.accept`] or [`method: Dialog.dismiss`] the dialog - otherwise the page will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog, and actions like click will never finish. :::note When no [`event: Page.dialog`] listeners are present, all dialogs are automatically dismissed. ::: ## event: Page.DOMContentLoaded - type: <[Page]> 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 [`option: acceptDownloads`] set to `true` when user needs access to the downloaded content. If [`option: acceptDownloads`] is not set, 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'); }); ``` ```py page.on("filechooser", lambda file_chooser: file_chooser.set_files("/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 - type: <[Page]> 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.pageError * langs: csharp, java - type: <[string]> ## 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')); ``` ```python async async with page.expect_event("popup") as page_info: page.evaluate("window.open('https://example.com')") popup = await page_info.value print(await popup.evaluate("location.href")) ``` ```python sync with page.expect_event("popup") as page_info: page.evaluate("window.open('https://example.com')") popup = page_info.value print(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. ## 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 browser // preload.js Math.random = () => 42; ``` ```js // In your playwright script, assuming the preload.js file is in same directory await page.addInitScript({ path: './preload.js' }); ``` ```python async # in your playwright script, assuming the preload.js file is in same directory await page.add_init_script(path="./preload.js") ``` ```python sync # in your playwright script, assuming the preload.js file is in same directory page.add_init_script(path="./preload.js") ``` :::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.script * langs: csharp, java - `script` <[string]|[path]> Script to be evaluated in all pages in the browser context. ### 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'); })(); ``` ```python async import asyncio from playwright.async_api import async_playwright async def run(playwright): webkit = playwright.webkit browser = await webkit.launch(headless=false) context = await browser.new_context() page = await context.new_page() await page.expose_binding("pageURL", lambda source: source["page"].url) await page.set_content("""
""") await page.click("button") async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` ```python sync from playwright.sync_api import sync_playwright def run(playwright): webkit = playwright.webkit browser = webkit.launch(headless=false) context = browser.new_context() page = context.new_page() page.expose_binding("pageURL", lambda source: source["page"].url) page.set_content("""
""") page.click("button") with sync_playwright() as playwright: run(playwright) ``` 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
`); ``` ```python async async def print(source, element): print(await element.text_content()) await page.expose_binding("clicked", print, handle=true) await page.set_content("""
Click me
Or click me
""") ``` ```python sync def print(source, element): print(element.text_content()) page.expose_binding("clicked", print, handle=true) page.set_content("""
Click me
Or click me
""") ``` ### param: Page.exposeBinding.name - `name` <[string]> Name of the function on the window object. ### param: Page.exposeBinding.callback - `callback` <[function]> Callback function that will be called in the Playwright's context. ### option: Page.exposeBinding.handle - `handle` <[boolean]> 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. ## async method: Page.exposeFunction The method adds a function called [`param: name`] on the `window` object of every frame in the page. When called, the function executes [`param: callback`] and returns a [Promise] which resolves to the return value of [`param: callback`]. If the [`param: callback`] returns a [Promise], it will be awaited. See [`method: BrowserContext.exposeFunction`] for context-wide exposed function. :::note Functions installed via [`method: Page.exposeFunction`] survive navigations. ::: An example of adding an `sha1` 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('sha1', text => crypto.createHash('sha1').update(text).digest('hex')); await page.setContent(`
`); await page.click('button'); })(); ``` ```python async import asyncio import hashlib from playwright.async_api import async_playwright async def sha1(text): m = hashlib.sha1() m.update(bytes(text, "utf8")) return m.hexdigest() async def run(playwright): webkit = playwright.webkit browser = await webkit.launch(headless=False) page = await browser.new_page() await page.expose_function("sha1", sha1) await page.set_content("""
""") await page.click("button") async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` ```python sync import hashlib from playwright.sync_api import sync_playwright def sha1(text): m = hashlib.sha1() m.update(bytes(text, "utf8")) return m.hexdigest() def run(playwright): webkit = playwright.webkit browser = webkit.launch(headless=False) page = browser.new_page() page.expose_function("sha1", sha1) page.set_content("""
""") page.click("button") with sync_playwright() as playwright: run(playwright) ``` ### param: Page.exposeFunction.name - `name` <[string]> Name of the function on the window object ### param: Page.exposeFunction.callback - `callback` <[function]> Callback function which will be called in Playwright's context. ## async method: Page.fill This method waits for an element matching [`param: selector`], waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling. If the element is inside the `