# 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(); })(); ``` ```java import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch(); BrowserContext context = browser.newContext(); Page page = context.newPage(); page.navigate("https://example.com"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png"))); 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) ``` ```csharp using Microsoft.Playwright; using System.Threading.Tasks; class PageExamples { public static async Task Run() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Webkit.LaunchAsync(); var page = await browser.NewPageAsync(); await page.GotoAsync("https://www.theverge.com"); await page.ScreenshotAsync(new PageScreenshotOptions { Path = "theverge.png" }); } } ``` 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!')); ``` ```java page.onLoad(p -> System.out.println("Page loaded!")); ``` ```py page.once("load", lambda: print("page loaded!")) ``` ```csharp page.Load += (_, _) => Console.WriteLine("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); ``` ```java Consumer logRequest = interceptedRequest -> { System.out.println("A request was made: " + interceptedRequest.url()); }; page.onRequest(logRequest); // Sometime later... page.offRequest(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) ``` ```csharp void PageLoadHandler(object _, IPage p) { Console.WriteLine("Page loaded!"); }; page.Load += PageLoadHandler; // Do some work... page.Load -= PageLoadHandler; ``` ## event: Page.close - argument: <[Page]> Emitted when the page closes. ## event: Page.console * langs: - alias-java: consoleMessage - argument: <[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', async msg => { const values = []; for (const arg of msg.args()) values.push(await arg.jsonValue()); console.log(...values); }); await page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); ``` ```java page.onConsoleMessage(msg -> { for (int i = 0; i < msg.args().size(); ++i) System.out.println(i + ": " + msg.args().get(i).jsonValue()); }); page.evaluate("() => console.log('hello', 5, {foo: 'bar'})"); ``` ```python async async def print_args(msg): values = [] for arg in msg.args: values.append(await arg.json_value()) print(values) 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'})") ``` ```csharp page.Console += async (_, msg) => { foreach (var arg in msg.Args) Console.WriteLine(await arg.JsonValueAsync()); }; await page.EvaluateAsync("console.log('hello', 5, { foo: 'bar' })"); ``` ## event: Page.crash - argument: <[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'. } ``` ```java try { // Crash might happen during a click. page.click("button"); // Or while waiting for an event. page.waitForPopup(() -> {}); } catch (PlaywrightException 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". ``` ```csharp try { // Crash might happen during a click. await page.ClickAsync("button"); // Or while waiting for an event. await page.WaitForPopup(); } catch (PlaywrightException e) { // When the page crashes, exception message contains "crash". } ``` ## event: Page.dialog - argument: <[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. ```js page.on('dialog', dialog => { dialog.accept(); }); ``` ```java page.onDialog(dialog -> { dialog.accept(); }); ``` ```python page.on("dialog", lambda dialog: dialog.accept()) ``` ```csharp page.RequestFailed += (_, request) => { Console.WriteLine(request.Url + " " + request.Failure); }; ``` :::note When no [`event: Page.dialog`] listeners are present, all dialogs are automatically dismissed. ::: ## event: Page.DOMContentLoaded - argument: <[Page]> Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched. ## event: Page.download - argument: <[Download]> Emitted when attachment download started. User can access basic file operations on downloaded content via the passed [Download] instance. ## event: Page.fileChooser - argument: <[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'); }); ``` ```java page.onFileChooser(fileChooser -> { fileChooser.setFiles(Paths.get("/tmp/myfile.pdf")); }); ``` ```py page.on("filechooser", lambda file_chooser: file_chooser.set_files("/tmp/myfile.pdf")) ``` ```csharp page.FileChooser += (_, fileChooser) => { fileChooser.SetFilesAsync(@"C:\temp\myfile.pdf"); }; ``` ## event: Page.frameAttached - argument: <[Frame]> Emitted when a frame is attached. ## event: Page.frameDetached - argument: <[Frame]> Emitted when a frame is detached. ## event: Page.frameNavigated - argument: <[Frame]> Emitted when a frame is navigated to a new url. ## event: Page.load - argument: <[Page]> Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. ## event: Page.pageError - argument: <[Error]> Emitted when an uncaught exception happens within the page. ```js // Log all uncaught errors to the terminal page.on('pageerror', exception => { console.log(`Uncaught exception: "${exception}"`); }); // Navigate to a page with an exception. await page.goto('data:text/html,'); ``` ```java // Log all uncaught errors to the terminal page.onPageError(exception -> { System.out.println("Uncaught exception: " + exception); }); // Navigate to a page with an exception. page.navigate("data:text/html,"); ``` ```python async # Log all uncaught errors to the terminal page.on("pageerror", lambda exc: print(f"uncaught exception: {exc}")) # Navigate to a page with an exception. await page.goto("data:text/html,") ``` ```python sync # Log all uncaught errors to the terminal page.on("pageerror", lambda exc: print(f"uncaught exception: {exc}")) # Navigate to a page with an exception. page.goto("data:text/html,") ``` ```csharp // Log all uncaught errors to the terminal page.PageError += (_, exception) => { Console.WriteLine("Uncaught exception: " + exception); }; ``` ## event: Page.pageError * langs: csharp, java - argument: <[string]> ## event: Page.popup - argument: <[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 // Note that Promise.all prevents a race condition // between evaluating and waiting for the popup. const [popup] = await Promise.all([ // It is important to call waitForEvent first. page.waitForEvent('popup'), // Opens the popup. page.evaluate(() => window.open('https://example.com')), ]); console.log(await popup.evaluate('location.href')); ``` ```java Page popup = page.waitForPopup(() -> { page.evaluate("() => window.open('https://example.com')"); }); System.out.println(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")) ``` ```csharp var popup = await page.RunAndWaitForPopupAsync(async () => { await page.EvaluateAsync("() => window.open('https://microsoft.com')"); }); Console.WriteLine(await popup.EvaluateAsync("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 - argument: <[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 - argument: <[Request]> Emitted when a request fails, for example by timing out. ```js page.on('requestfailed', request => { console.log(request.url() + ' ' + request.failure().errorText); }); ``` ```java page.onRequestFailed(request -> { System.out.println(request.url() + " " + request.failure()); }); ``` ```python page.on("requestfailed", lambda request: print(request.url + " " + request.failure.error_text)) ``` :::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`]. A request will only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error net::ERR_FAILED. ::: ## event: Page.requestFinished - argument: <[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 - argument: <[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 - argument: <[WebSocket]> Emitted when [WebSocket] request is sent. ## event: Page.worker - argument: <[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 * langs: csharp, js, python - 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' }); ``` ```java // In your playwright script, assuming the preload.js file is in same directory page.addInitScript(Paths.get("./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") ``` ```csharp await page.AddInitScriptAsync(new PageAddInitScriptOption { ScriptPath = "./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'); })(); ``` ```java import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch({ headless: false }); BrowserContext context = browser.newContext(); Page page = context.newPage(); page.exposeBinding("pageURL", (source, args) -> source.page().url()); page.setContent("\n" + "\n" + "
"); 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) ``` ```csharp using Microsoft.Playwright; using System.Threading.Tasks; class PageExamples { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Headless: false }); var page = await browser.NewPageAsync(); await page.ExposeBindingAsync("pageUrl", (source) => source.Page.Url); await page.SetContentAsync("\n" + "\n" + "
"); await page.ClickAsync("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
`); ``` ```java page.exposeBinding("clicked", (source, args) -> { ElementHandle element = (ElementHandle) args[0]; System.out.println(element.textContent()); return null; }, new Page.ExposeBindingOptions().setHandle(true)); page.setContent("" + "\n" + "
Click me
\n" + "
Or click me
\n"); ``` ```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
""") ``` ```csharp var result = new TaskCompletionSource(); await page.ExposeBindingAsync("clicked", async (BindingSource _, IJSHandle t) => { return result.TrySetResult(await t.AsElement().TextContentAsync()); }); await page.SetContentAsync("\n" + "
Click me
\n" + "
Or click me
\n"); await page.ClickAsync("div"); Console.WriteLine(await result.Task); ``` ### 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 a `sha256` 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('sha256', text => crypto.createHash('sha256').update(text).digest('hex')); await page.setContent(`
`); await page.click('button'); })(); ``` ```java import com.microsoft.playwright.*; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch({ headless: false }); Page page = browser.newPage(); page.exposeFunction("sha256", args -> { String text = (String) args[0]; MessageDigest crypto; try { crypto = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { return null; } byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(token); }); page.setContent("\n" + "\n" + "
\n"); page.click("button"); } } } ``` ```python async import asyncio import hashlib from playwright.async_api import async_playwright def sha256(text): m = hashlib.sha256() 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("sha256", sha256) 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 sha256(text): m = hashlib.sha256() 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("sha256", sha256) page.set_content("""
""") page.click("button") with sync_playwright() as playwright: run(playwright) ``` ```csharp using Microsoft.Playwright; using System; using System.Security.Cryptography; using System.Threading.Tasks; class PageExamples { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions { Headless: false }); var page = await browser.NewPageAsync(); await page.ExposeFunctionAsync("sha256", (string input) => { return Convert.ToBase64String( SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input))); }); await page.SetContentAsync("\n" + "\n" + "
"); await page.ClickAsync("button"); Console.WriteLine(await page.TextContentAsync("div")); } } ``` ### 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. Note that you can pass an empty string to clear the input field. If the target element is not an ``, `