Playwright文档 - Page(页面)


Page 提供了与浏览器中的单个选项卡或Chromium 中的扩展后台页面进行交互的方法。一个浏览器实例可能有多个页面实例。

class: Page

  • since: v1.8
  • 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:

1const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. 2 3(async () => { 4 const browser = await webkit.launch(); 5 const context = await browser.newContext(); 6 const page = await context.newPage(); 7 await page.goto('https://example.com'); 8 await page.screenshot({ path: 'screenshot.png' }); 9 await browser.close(); 10})(); 11
1import com.microsoft.playwright.*; 2 3public class Example { 4 public static void main(String[] args) { 5 try (Playwright playwright = Playwright.create()) { 6 BrowserType webkit = playwright.webkit(); 7 Browser browser = webkit.launch(); 8 BrowserContext context = browser.newContext(); 9 Page page = context.newPage(); 10 page.navigate("https://example.com"); 11 page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png"))); 12 browser.close(); 13 } 14 } 15} 16
1import asyncio 2from playwright.async_api import async_playwright, Playwright 3 4async def run(playwright: Playwright): 5 webkit = playwright.webkit 6 browser = await webkit.launch() 7 context = await browser.new_context() 8 page = await context.new_page() 9 await page.goto("https://example.com") 10 await page.screenshot(path="screenshot.png") 11 await browser.close() 12 13async def main(): 14 async with async_playwright() as playwright: 15 await run(playwright) 16asyncio.run(main()) 17
1from playwright.sync_api import sync_playwright, Playwright 2 3def run(playwright: Playwright): 4 webkit = playwright.webkit 5 browser = webkit.launch() 6 context = browser.new_context() 7 page = context.new_page() 8 page.goto("https://example.com") 9 page.screenshot(path="screenshot.png") 10 browser.close() 11 12with sync_playwright() as playwright: 13 run(playwright) 14
1using Microsoft.Playwright; 2using System.Threading.Tasks; 3 4class PageExamples 5{ 6 public static async Task Run() 7 { 8 using var playwright = await Playwright.CreateAsync(); 9 await using var browser = await playwright.Webkit.LaunchAsync(); 10 var page = await browser.NewPageAsync(); 11 await page.GotoAsync("https://www.theverge.com"); 12 await page.ScreenshotAsync(new() { Path = "theverge.png" }); 13 } 14} 15

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:

1page.once('load', () => console.log('Page loaded!')); 2
1page.onLoad(p -> System.out.println("Page loaded!")); 2
1page.once("load", lambda: print("page loaded!")) 2
1page.Load += (_, _) => Console.WriteLine("Page loaded!"); 2

To unsubscribe from events use the removeListener method:

1function logRequest(interceptedRequest) { 2 console.log('A request was made:', interceptedRequest.url()); 3} 4page.on('request', logRequest); 5// Sometime later... 6page.removeListener('request', logRequest); 7
1Consumer<Request> logRequest = interceptedRequest -> { 2 System.out.println("A request was made: " + interceptedRequest.url()); 3}; 4page.onRequest(logRequest); 5// Sometime later... 6page.offRequest(logRequest); 7
1def log_request(intercepted_request): 2 print("a request was made:", intercepted_request.url) 3page.on("request", log_request) 4# sometime later... 5page.remove_listener("request", log_request) 6
1void PageLoadHandler(object _, IPage p) { 2 Console.WriteLine("Page loaded!"); 3}; 4 5page.Load += PageLoadHandler; 6// Do some work... 7page.Load -= PageLoadHandler; 8

event: Page.close

  • since: v1.8
  • argument: <[Page]>

Emitted when the page closes.

event: Page.console

  • since: v1.8
  • 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 are available on the [ConsoleMessage] event handler argument.

Usage

1page.on('console', async msg => { 2 const values = []; 3 for (const arg of msg.args()) 4 values.push(await arg.jsonValue()); 5 console.log(...values); 6}); 7await page.evaluate(() => console.log('hello', 5, { foo: 'bar' })); 8
1page.onConsoleMessage(msg -> { 2 for (int i = 0; i < msg.args().size(); ++i) 3 System.out.println(i + ": " + msg.args().get(i).jsonValue()); 4}); 5page.evaluate("() => console.log('hello', 5, { foo: 'bar' })"); 6
1async def print_args(msg): 2 values = [] 3 for arg in msg.args: 4 values.append(await arg.json_value()) 5 print(values) 6 7page.on("console", print_args) 8await page.evaluate("console.log('hello', 5, { foo: 'bar' })") 9
1def print_args(msg): 2 for arg in msg.args: 3 print(arg.json_value()) 4 5page.on("console", print_args) 6page.evaluate("console.log('hello', 5, { foo: 'bar' })") 7
1page.Console += async (_, msg) => 2{ 3 foreach (var arg in msg.Args) 4 Console.WriteLine(await arg.JsonValueAsync<object>()); 5}; 6 7await page.EvaluateAsync("console.log('hello', 5, { foo: 'bar' })"); 8

event: Page.crash

  • since: v1.8
  • 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:

1try { 2 // Crash might happen during a click. 3 await page.click('button'); 4 // Or while waiting for an event. 5 await page.waitForEvent('popup'); 6} catch (e) { 7 // When the page crashes, exception message contains 'crash'. 8} 9
1try { 2 // Crash might happen during a click. 3 page.click("button"); 4 // Or while waiting for an event. 5 page.waitForPopup(() -> {}); 6} catch (PlaywrightException e) { 7 // When the page crashes, exception message contains "crash". 8} 9
1try: 2 # crash might happen during a click. 3 await page.click("button") 4 # or while waiting for an event. 5 await page.wait_for_event("popup") 6except Error as e: 7 pass 8 # when the page crashes, exception message contains "crash". 9
1try: 2 # crash might happen during a click. 3 page.click("button") 4 # or while waiting for an event. 5 page.wait_for_event("popup") 6except Error as e: 7 pass 8 # when the page crashes, exception message contains "crash". 9
1try { 2 // Crash might happen during a click. 3 await page.ClickAsync("button"); 4 // Or while waiting for an event. 5 await page.WaitForPopup(); 6} catch (PlaywrightException e) { 7 // When the page crashes, exception message contains "crash". 8} 9

event: Page.dialog

  • since: v1.8
  • 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 waiting for the dialog, and actions like click will never finish.

Usage

1page.on('dialog', dialog => { 2 dialog.accept(); 3}); 4
1page.onDialog(dialog -> { 2 dialog.accept(); 3}); 4
1page.on("dialog", lambda dialog: dialog.accept()) 2
1page.RequestFailed += (_, request) => 2{ 3 Console.WriteLine(request.Url + " " + request.Failure); 4}; 5

:::note When no [event: Page.dialog] or [event: BrowserContext.dialog] listeners are present, all dialogs are automatically dismissed. :::

event: Page.DOMContentLoaded

  • since: v1.9
  • argument: <[Page]>

Emitted when the JavaScript DOMContentLoaded event is dispatched.

event: Page.download

  • since: v1.8
  • argument: <[Download]>

Emitted when attachment download started. User can access basic file operations on downloaded content via the passed [Download] instance.

event: Page.fileChooser

  • since: v1.9
  • argument: <[FileChooser]>

Emitted when a file chooser is supposed to appear, such as after clicking the <input type=file>. Playwright can respond to it via setting the input files using [method: FileChooser.setFiles] that can be uploaded after that.

1page.on('filechooser', async fileChooser => { 2 await fileChooser.setFiles(path.join(__dirname, '/tmp/myfile.pdf')); 3}); 4
1page.onFileChooser(fileChooser -> { 2 fileChooser.setFiles(Paths.get("/tmp/myfile.pdf")); 3}); 4
1page.on("filechooser", lambda file_chooser: file_chooser.set_files("/tmp/myfile.pdf")) 2
1page.FileChooser += (_, fileChooser) => 2{ 3 fileChooser.SetFilesAsync(@"C:\temp\myfile.pdf"); 4}; 5

event: Page.frameAttached

  • since: v1.9
  • argument: <[Frame]>

Emitted when a frame is attached.

event: Page.frameDetached

  • since: v1.9
  • argument: <[Frame]>

Emitted when a frame is detached.

event: Page.frameNavigated

  • since: v1.9
  • argument: <[Frame]>

Emitted when a frame is navigated to a new url.

event: Page.load

  • since: v1.8
  • argument: <[Page]>

Emitted when the JavaScript load event is dispatched.

event: Page.pageError

  • since: v1.9
  • argument: <[Error]>

Emitted when an uncaught exception happens within the page.

1// Log all uncaught errors to the terminal 2page.on('pageerror', exception => { 3 console.log(`Uncaught exception: "${exception}"`); 4}); 5 6// Navigate to a page with an exception. 7await page.goto('data:text/html,<script>throw new Error("Test")</script>'); 8
1// Log all uncaught errors to the terminal 2page.onPageError(exception -> { 3 System.out.println("Uncaught exception: " + exception); 4}); 5 6// Navigate to a page with an exception. 7page.navigate("data:text/html,<script>throw new Error('Test')</script>"); 8
1# Log all uncaught errors to the terminal 2page.on("pageerror", lambda exc: print(f"uncaught exception: {exc}")) 3 4# Navigate to a page with an exception. 5await page.goto("data:text/html,<script>throw new Error('test')</script>") 6
1# Log all uncaught errors to the terminal 2page.on("pageerror", lambda exc: print(f"uncaught exception: {exc}")) 3 4# Navigate to a page with an exception. 5page.goto("data:text/html,<script>throw new Error('test')</script>") 6
1// Log all uncaught errors to the terminal 2page.PageError += (_, exception) => 3{ 4 Console.WriteLine("Uncaught exception: " + exception); 5}; 6

event: Page.pageError

  • since: v1.9
  • langs: csharp, java
  • argument: <[string]>

event: Page.popup

  • since: v1.8
  • 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.

1// Start waiting for popup before clicking. Note no await. 2const popupPromise = page.waitForEvent('popup'); 3await page.getByText('open the popup').click(); 4const popup = await popupPromise; 5console.log(await popup.evaluate('location.href')); 6
1Page popup = page.waitForPopup(() -> { 2 page.getByText("open the popup").click(); 3}); 4System.out.println(popup.evaluate("location.href")); 5
1async with page.expect_event("popup") as page_info: 2 await page.get_by_text("open the popup").click() 3popup = await page_info.value 4print(await popup.evaluate("location.href")) 5
1with page.expect_event("popup") as page_info: 2 page.get_by_text("open the popup").click() 3popup = page_info.value 4print(popup.evaluate("location.href")) 5
1var popup = await page.RunAndWaitForPopupAsync(async () => 2{ 3 await page.GetByText("open the popup").ClickAsync(); 4}); 5Console.WriteLine(await popup.EvaluateAsync<string>("location.href")); 6

:::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

  • since: v1.8
  • 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

  • since: v1.9
  • argument: <[Request]>

Emitted when a request fails, for example by timing out.

1page.on('requestfailed', request => { 2 console.log(request.url() + ' ' + request.failure().errorText); 3}); 4
1page.onRequestFailed(request -> { 2 System.out.println(request.url() + " " + request.failure()); 3}); 4
1page.on("requestfailed", lambda request: print(request.url + " " + request.failure.error_text)) 2

:::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

  • since: v1.9
  • 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

  • since: v1.8
  • 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

  • since: v1.9
  • argument: <[WebSocket]>

Emitted when [WebSocket] request is sent.

event: Page.worker

  • since: v1.8
  • argument: <[Worker]>

Emitted when a dedicated WebWorker is spawned by the page.

property: Page.accessibility

  • since: v1.8
  • langs: csharp, js, python
  • deprecated: This property is discouraged. Please use other libraries such as Axe if you need to test page accessibility. See our Node.js guide for integration with Axe.
  • type: <[Accessibility]>

async method: Page.addInitScript

  • since: v1.8

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.

Usage

An example of overriding Math.random before the page loads:

1// preload.js 2Math.random = () => 42; 3
1// In your playwright script, assuming the preload.js file is in same directory 2await page.addInitScript({ path: './preload.js' }); 3
1await page.addInitScript(mock => { 2 window.mock = mock; 3}, mock); 4
1// In your playwright script, assuming the preload.js file is in same directory 2page.addInitScript(Paths.get("./preload.js")); 3
1# in your playwright script, assuming the preload.js file is in same directory 2await page.add_init_script(path="./preload.js") 3
1# in your playwright script, assuming the preload.js file is in same directory 2page.add_init_script(path="./preload.js") 3
1await page.AddInitScriptAsync(scriptPath: "./preload.js"); 2

:::note The order of evaluation of multiple scripts installed via [method: BrowserContext.addInitScript] and [method: Page.addInitScript] is not defined. :::

param: Page.addInitScript.script

  • since: v1.8
  • 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

  • since: v1.8
  • langs: csharp, java
  • script <[string]|[path]>

Script to be evaluated in all pages in the browser context.

param: Page.addInitScript.arg

  • since: v1.8
  • langs: js
  • arg ?<[Serializable]>

Optional argument to pass to [param: script] (only supported when passing a function).

param: Page.addInitScript.path

  • since: v1.8
  • langs: python
  • path ?<[path]>

Path to the JavaScript file. If path is a relative path, then it is resolved relative to the current working directory. Optional.

param: Page.addInitScript.script

  • since: v1.8
  • langs: python
  • script ?<[string]>

Script to be evaluated in all pages in the browser context. Optional.

async method: Page.addScriptTag

  • since: v1.8
  • returns: <[ElementHandle]>

Adds 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.

option: Page.addScriptTag.url

  • since: v1.8
  • url <[string]>

URL of a script to be added.

option: Page.addScriptTag.path

  • since: v1.8
  • path <[path]>

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.

option: Page.addScriptTag.content

  • since: v1.8
  • content <[string]>

Raw JavaScript content to be injected into frame.

option: Page.addScriptTag.type

  • since: v1.8
  • type <[string]>

Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.

async method: Page.addStyleTag

  • since: v1.8
  • returns: <[ElementHandle]>

Adds 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.

option: Page.addStyleTag.url

  • since: v1.8
  • url <[string]>

URL of the <link> tag.

option: Page.addStyleTag.path

  • since: v1.8
  • path <[path]>

Path to the CSS file to be injected into frame. If path is a relative path, then it is resolved relative to the current working directory.

option: Page.addStyleTag.content

  • since: v1.8
  • content <[string]>

Raw CSS content to be injected into frame.

async method: Page.bringToFront

  • since: v1.8

Brings page to front (activates tab).

async method: Page.check

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.check] instead. Read more about locators.

This method checks an element matching [param: selector] by performing the following steps:

  1. Find an element matching [param: selector]. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
  3. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  4. Scroll the element into view if needed.
  5. Use [property: Page.mouse] to click in the center of the element.
  6. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  7. Ensure that the element is now checked. If not, this method throws.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

param: Page.check.selector = %%-input-selector-%%

  • since: v1.8

option: Page.check.force = %%-input-force-%%

  • since: v1.8

option: Page.check.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.check.position = %%-input-position-%%

  • since: v1.11

option: Page.check.strict = %%-input-strict-%%

  • since: v1.14

option: Page.check.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.check.timeout = %%-input-timeout-js-%%

  • since: v1.8

option: Page.check.trial = %%-input-trial-%%

  • since: v1.11

async method: Page.click

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.click] instead. Read more about locators.

This method clicks an element matching [param: selector] by performing the following steps:

  1. Find an element matching [param: selector]. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element, or the specified [option: position].
  5. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

param: Page.click.selector = %%-input-selector-%%

  • since: v1.8

option: Page.click.button = %%-input-button-%%

  • since: v1.8

option: Page.click.clickCount = %%-input-click-count-%%

  • since: v1.8

option: Page.click.delay = %%-input-down-up-delay-%%

  • since: v1.8

option: Page.click.force = %%-input-force-%%

  • since: v1.8

option: Page.click.modifiers = %%-input-modifiers-%%

  • since: v1.8

option: Page.click.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.click.position = %%-input-position-%%

  • since: v1.8

option: Page.click.strict = %%-input-strict-%%

  • since: v1.14

option: Page.click.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.click.timeout = %%-input-timeout-js-%%

  • since: v1.8

option: Page.click.trial = %%-input-trial-%%

  • since: v1.11

async method: Page.close

  • since: v1.8

If [option: runBeforeUnload] is false, does not run any unload handlers and waits for the page to be closed. If [option: 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.

:::note if [option: runBeforeUnload] is passed as true, a beforeunload dialog might be summoned and should be handled manually via [event: Page.dialog] event. :::

option: Page.close.runBeforeUnload

  • since: v1.8
  • runBeforeUnload <[boolean]>

Defaults to false. Whether to run the before unload page handlers.

async method: Page.content

  • since: v1.8
  • returns: <[string]>

Gets the full HTML contents of the page, including the doctype.

method: Page.context

  • since: v1.8
  • returns: <[BrowserContext]>

Get the browser context that the page belongs to.

property: Page.coverage

  • since: v1.8
  • langs: js
  • type: <[Coverage]>

:::note Only available for Chromium atm. :::

Browser-specific Coverage implementation. See Coverage for more details.

async method: Page.dblclick

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.dblclick] instead. Read more about locators.
  • langs:
    • alias-csharp: DblClickAsync

This method double clicks an element matching [param: selector] by performing the following steps:

  1. Find an element matching [param: selector]. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to double click in the center of the element, or the specified [option: position].
  5. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set. Note that if the first click of the dblclick() triggers a navigation event, this method will throw.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

:::note page.dblclick() dispatches two click events and a single dblclick event. :::

param: Page.dblclick.selector = %%-input-selector-%%

  • since: v1.8

option: Page.dblclick.button = %%-input-button-%%

  • since: v1.8

option: Page.dblclick.force = %%-input-force-%%

  • since: v1.8

option: Page.dblclick.delay = %%-input-down-up-delay-%%

  • since: v1.8

option: Page.dblclick.modifiers = %%-input-modifiers-%%

  • since: v1.8

option: Page.dblclick.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.dblclick.position = %%-input-position-%%

  • since: v1.8

option: Page.dblclick.strict = %%-input-strict-%%

  • since: v1.14

option: Page.dblclick.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.dblclick.timeout = %%-input-timeout-js-%%

  • since: v1.8

option: Page.dblclick.trial = %%-input-trial-%%

  • since: v1.11

async method: Page.dispatchEvent

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.dispatchEvent] instead. Read more about locators.

The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is dispatched. This is equivalent to calling element.click().

Usage

1await page.dispatchEvent('button#submit', 'click'); 2
1page.dispatchEvent("button#submit", "click"); 2
1await page.dispatch_event("button#submit", "click") 2
1page.dispatch_event("button#submit", "click") 2
1await page.DispatchEventAsync("button#submit", "click"); 2

Under the hood, it creates an instance of an event based on the given [param: type], initializes it with [param: eventInit] properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

Since [param: eventInit] is event-specific, please refer to the events documentation for the lists of initial properties:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

1// Note you can only create DataTransfer in Chromium and Firefox 2const dataTransfer = await page.evaluateHandle(() => new DataTransfer()); 3await page.dispatchEvent('#source', 'dragstart', { dataTransfer }); 4
1// Note you can only create DataTransfer in Chromium and Firefox 2JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()"); 3Map<String, Object> arg = new HashMap<>(); 4arg.put("dataTransfer", dataTransfer); 5page.dispatchEvent("#source", "dragstart", arg); 6
1# note you can only create data_transfer in chromium and firefox 2data_transfer = await page.evaluate_handle("new DataTransfer()") 3await page.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer }) 4
1# note you can only create data_transfer in chromium and firefox 2data_transfer = page.evaluate_handle("new DataTransfer()") 3page.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer }) 4
1var dataTransfer = await page.EvaluateHandleAsync("() => new DataTransfer()"); 2await page.DispatchEventAsync("#source", "dragstart", new { dataTransfer }); 3

param: Page.dispatchEvent.selector = %%-input-selector-%%

  • since: v1.8

param: Page.dispatchEvent.type

  • since: v1.8
  • type <[string]>

DOM event type: "click", "dragstart", etc.

param: Page.dispatchEvent.eventInit

  • since: v1.8
  • eventInit ?<[EvaluationArgument]>

Optional event-specific initialization properties.

option: Page.dispatchEvent.strict = %%-input-strict-%%

  • since: v1.14

option: Page.dispatchEvent.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.dispatchEvent.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.dragAndDrop

  • since: v1.13

This 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

1await page.dragAndDrop('#source', '#target'); 2// or specify exact positions relative to the top-left corners of the elements: 3await page.dragAndDrop('#source', '#target', { 4 sourcePosition: { x: 34, y: 7 }, 5 targetPosition: { x: 10, y: 20 }, 6}); 7
1page.dragAndDrop("#source", '#target'); 2// or specify exact positions relative to the top-left corners of the elements: 3page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions() 4 .setSourcePosition(34, 7).setTargetPosition(10, 20)); 5
1await page.drag_and_drop("#source", "#target") 2# or specify exact positions relative to the top-left corners of the elements: 3await page.drag_and_drop( 4 "#source", 5 "#target", 6 source_position={"x": 34, "y": 7}, 7 target_position={"x": 10, "y": 20} 8) 9
1page.drag_and_drop("#source", "#target") 2# or specify exact positions relative to the top-left corners of the elements: 3page.drag_and_drop( 4 "#source", 5 "#target", 6 source_position={"x": 34, "y": 7}, 7 target_position={"x": 10, "y": 20} 8) 9
1await Page.DragAndDropAsync("#source", "#target"); 2// or specify exact positions relative to the top-left corners of the elements: 3await Page.DragAndDropAsync("#source", "#target", new() 4{ 5 SourcePosition = new() { X = 34, Y = 7 }, 6 TargetPosition = new() { X = 10, Y = 20 }, 7}); 8

param: Page.dragAndDrop.source = %%-input-source-%%

  • since: v1.13

param: Page.dragAndDrop.target = %%-input-target-%%

  • since: v1.13

option: Page.dragAndDrop.force = %%-input-force-%%

  • since: v1.13

option: Page.dragAndDrop.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.13

option: Page.dragAndDrop.strict = %%-input-strict-%%

  • since: v1.14

option: Page.dragAndDrop.timeout = %%-input-timeout-%%

  • since: v1.13

option: Page.dragAndDrop.timeout = %%-input-timeout-js-%%

  • since: v1.13

option: Page.dragAndDrop.trial = %%-input-trial-%%

  • since: v1.13

option: Page.dragAndDrop.sourcePosition = %%-input-source-position-%%

  • since: v1.14

option: Page.dragAndDrop.targetPosition = %%-input-target-position-%%

  • since: v1.14

async method: Page.emulateMedia

  • since: v1.8

This method changes the CSS media type through the media argument, and/or the 'prefers-colors-scheme' media feature, using the colorScheme argument.

Usage

1await page.evaluate(() => matchMedia('screen').matches); 2// → true 3await page.evaluate(() => matchMedia('print').matches); 4// → false 5 6await page.emulateMedia({ media: 'print' }); 7await page.evaluate(() => matchMedia('screen').matches); 8// → false 9await page.evaluate(() => matchMedia('print').matches); 10// → true 11 12await page.emulateMedia({}); 13await page.evaluate(() => matchMedia('screen').matches); 14// → true 15await page.evaluate(() => matchMedia('print').matches); 16// → false 17
1page.evaluate("() => matchMedia('screen').matches"); 2// → true 3page.evaluate("() => matchMedia('print').matches"); 4// → false 5 6page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT)); 7page.evaluate("() => matchMedia('screen').matches"); 8// → false 9page.evaluate("() => matchMedia('print').matches"); 10// → true 11 12page.emulateMedia(new Page.EmulateMediaOptions()); 13page.evaluate("() => matchMedia('screen').matches"); 14// → true 15page.evaluate("() => matchMedia('print').matches"); 16// → false 17
1await page.evaluate("matchMedia('screen').matches") 2# → True 3await page.evaluate("matchMedia('print').matches") 4# → False 5 6await page.emulate_media(media="print") 7await page.evaluate("matchMedia('screen').matches") 8# → False 9await page.evaluate("matchMedia('print').matches") 10# → True 11 12await page.emulate_media() 13await page.evaluate("matchMedia('screen').matches") 14# → True 15await page.evaluate("matchMedia('print').matches") 16# → False 17
1page.evaluate("matchMedia('screen').matches") 2# → True 3page.evaluate("matchMedia('print').matches") 4# → False 5 6page.emulate_media(media="print") 7page.evaluate("matchMedia('screen').matches") 8# → False 9page.evaluate("matchMedia('print').matches") 10# → True 11 12page.emulate_media() 13page.evaluate("matchMedia('screen').matches") 14# → True 15page.evaluate("matchMedia('print').matches") 16# → False 17
1await page.EvaluateAsync("() => matchMedia('screen').matches"); 2// → true 3await page.EvaluateAsync("() => matchMedia('print').matches"); 4// → false 5 6await page.EmulateMediaAsync(new() { Media = Media.Print }); 7await page.EvaluateAsync("() => matchMedia('screen').matches"); 8// → false 9await page.EvaluateAsync("() => matchMedia('print').matches"); 10// → true 11 12await page.EmulateMediaAsync(new() { Media = Media.Screen }); 13await page.EvaluateAsync("() => matchMedia('screen').matches"); 14// → true 15await page.EvaluateAsync("() => matchMedia('print').matches"); 16// → false 17
1await page.emulateMedia({ colorScheme: 'dark' }); 2await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches); 3// → true 4await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches); 5// → false 6await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches); 7// → false 8
1page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK)); 2page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches"); 3// → true 4page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches"); 5// → false 6page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches"); 7// → false 8
1await page.emulate_media(color_scheme="dark") 2await page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches") 3# → True 4await page.evaluate("matchMedia('(prefers-color-scheme: light)').matches") 5# → False 6await page.evaluate("matchMedia('(prefers-color-scheme: no-preference)').matches") 7# → False 8
1page.emulate_media(color_scheme="dark") 2page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches") 3# → True 4page.evaluate("matchMedia('(prefers-color-scheme: light)').matches") 5# → False 6page.evaluate("matchMedia('(prefers-color-scheme: no-preference)').matches") 7
1await page.EmulateMediaAsync(new() { ColorScheme = ColorScheme.Dark }); 2await page.EvaluateAsync("matchMedia('(prefers-color-scheme: dark)').matches"); 3// → true 4await page.EvaluateAsync("matchMedia('(prefers-color-scheme: light)').matches"); 5// → false 6await page.EvaluateAsync("matchMedia('(prefers-color-scheme: no-preference)').matches"); 7// → false 8

option: Page.emulateMedia.media

  • since: v1.9
  • langs: js, java
  • media <null|[Media]<"screen"|"print">>

Changes the CSS media type of the page. The only allowed values are 'screen', 'print' and null. Passing null disables CSS media emulation.

option: Page.emulateMedia.media

  • since: v1.9
  • langs: csharp, python
  • media <[Media]<"screen"|"print"|"null">>

Changes the CSS media type of the page. The only allowed values are 'Screen', 'Print' and 'Null'. Passing 'Null' disables CSS media emulation.

option: Page.emulateMedia.colorScheme

  • since: v1.9
  • langs: js, java
  • colorScheme <null|[ColorScheme]<"light"|"dark"|"no-preference">>

Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'. Passing null disables color scheme emulation.

option: Page.emulateMedia.colorScheme

  • since: v1.9
  • langs: csharp, python
  • colorScheme <[ColorScheme]<"light"|"dark"|"no-preference"|"null">>

Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'. Passing 'Null' disables color scheme emulation.

option: Page.emulateMedia.reducedMotion

  • since: v1.12
  • langs: js, java
  • reducedMotion <null|[ReducedMotion]<"reduce"|"no-preference">>

Emulates 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. Passing null disables reduced motion emulation.

option: Page.emulateMedia.reducedMotion

  • since: v1.12
  • langs: csharp, python
  • reducedMotion <[ReducedMotion]<"reduce"|"no-preference"|"null">>

Emulates 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. Passing null disables reduced motion emulation.

option: Page.emulateMedia.forcedColors

  • since: v1.15
  • langs: js, java
  • forcedColors <null|[ForcedColors]<"active"|"none">>

Emulates 'forced-colors' media feature, supported values are 'active' and 'none'. Passing null disables forced colors emulation.

option: Page.emulateMedia.forcedColors

  • since: v1.15
  • langs: csharp, python
  • forcedColors <[ForcedColors]<"active"|"none"|"null">>

async method: Page.evalOnSelector

  • since: v1.9
  • discouraged: This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests. Use [method: Locator.evaluate], other [Locator] helper methods or web-first assertions instead.
  • langs:
    • alias-python: eval_on_selector
    • alias-js: $eval
  • returns: <[Serializable]>

The method finds an element matching the specified selector within the page and passes it as a first argument to [param: expression]. If no elements match the selector, the method throws an error. Returns the value of [param: expression].

If [param: expression] returns a [Promise], then [method: Page.evalOnSelector] would wait for the promise to resolve and return its value.

Usage

1const searchValue = await page.$eval('#search', el => el.value); 2const preloadHref = await page.$eval('link[rel=preload]', el => el.href); 3const html = await page.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello'); 4// In TypeScript, this example requires an explicit type annotation (HTMLLinkElement) on el: 5const preloadHrefTS = await page.$eval('link[rel=preload]', (el: HTMLLinkElement) => el.href); 6
1String searchValue = (String) page.evalOnSelector("#search", "el => el.value"); 2String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href"); 3String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello"); 4
1search_value = await page.eval_on_selector("#search", "el => el.value") 2preload_href = await page.eval_on_selector("link[rel=preload]", "el => el.href") 3html = await page.eval_on_selector(".main-container", "(e, suffix) => e.outer_html + suffix", "hello") 4
1search_value = page.eval_on_selector("#search", "el => el.value") 2preload_href = page.eval_on_selector("link[rel=preload]", "el => el.href") 3html = page.eval_on_selector(".main-container", "(e, suffix) => e.outer_html + suffix", "hello") 4
1var searchValue = await page.EvalOnSelectorAsync<string>("#search", "el => el.value"); 2var preloadHref = await page.EvalOnSelectorAsync<string>("link[rel=preload]", "el => el.href"); 3var html = await page.EvalOnSelectorAsync(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello"); 4

param: Page.evalOnSelector.selector = %%-query-selector-%%

  • since: v1.9

param: Page.evalOnSelector.expression = %%-evaluate-expression-%%

  • since: v1.9

param: Page.evalOnSelector.expression = %%-js-evalonselector-pagefunction-%%

  • since: v1.9

param: Page.evalOnSelector.arg

  • since: v1.9
  • arg ?<[EvaluationArgument]>

Optional argument to pass to [param: expression].

option: Page.evalOnSelector.strict = %%-input-strict-%%

  • since: v1.14

async method: Page.evalOnSelectorAll

  • since: v1.9
  • discouraged: In most cases, [method: Locator.evaluateAll], other [Locator] helper methods and web-first assertions do a better job.
  • langs:
    • alias-python: eval_on_selector_all
    • alias-js: $$eval
  • 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: expression]. Returns the result of [param: expression] invocation.

If [param: expression] returns a [Promise], then [method: Page.evalOnSelectorAll] would wait for the promise to resolve and return its value.

Usage

1const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); 2
1boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10); 2
1div_counts = await page.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10) 2
1div_counts = page.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10) 2
1var divsCount = await page.EvalOnSelectorAllAsync<bool>("div", "(divs, min) => divs.length >= min", 10); 2

param: Page.evalOnSelectorAll.selector = %%-query-selector-%%

  • since: v1.9

param: Page.evalOnSelectorAll.expression = %%-evaluate-expression-%%

  • since: v1.9

param: Page.evalOnSelectorAll.expression = %%-js-evalonselectorall-pagefunction-%%

  • since: v1.9

param: Page.evalOnSelectorAll.arg

  • since: v1.9
  • arg ?<[EvaluationArgument]>

Optional argument to pass to [param: expression].

async method: Page.evaluate

  • since: v1.8
  • returns: <[Serializable]>

Returns the value of the [param: expression] invocation.

If the function passed to the [method: Page.evaluate] returns a [Promise], then [method: Page.evaluate] would wait for the promise to resolve and return its value.

If the function passed to the [method: Page.evaluate] returns a non-[Serializable] value, then [method: 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 [param: expression]:

1const result = await page.evaluate(([x, y]) => { 2 return Promise.resolve(x * y); 3}, [7, 8]); 4console.log(result); // prints "56" 5
1Object result = page.evaluate("([x, y]) => {\n" + 2 " return Promise.resolve(x * y);\n" + 3 "}", Arrays.asList(7, 8)); 4System.out.println(result); // prints "56" 5
1result = await page.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8]) 2print(result) # prints "56" 3
1result = page.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8]) 2print(result) # prints "56" 3
1var result = await page.EvaluateAsync<int>("([x, y]) => Promise.resolve(x * y)", new[] { 7, 8 }); 2Console.WriteLine(result); 3

A string can also be passed in instead of a function:

1console.log(await page.evaluate('1 + 2')); // prints "3" 2const x = 10; 3console.log(await page.evaluate(`1 + ${x}`)); // prints "11" 4
1System.out.println(page.evaluate("1 + 2")); // prints "3" 2
1print(await page.evaluate("1 + 2")) # prints "3" 2x = 10 3print(await page.evaluate(f"1 + {x}")) # prints "11" 4
1print(page.evaluate("1 + 2")) # prints "3" 2x = 10 3print(page.evaluate(f"1 + {x}")) # prints "11" 4
1Console.WriteLine(await page.EvaluateAsync<int>("1 + 2")); // prints "3" 2

[ElementHandle] instances can be passed as an argument to the [method: Page.evaluate]:

1const bodyHandle = await page.evaluate('document.body'); 2const html = await page.evaluate<string, HTMLElement>(([body, suffix]) => 3 body.innerHTML + suffix, [bodyHandle, 'hello'] 4); 5await bodyHandle.dispose(); 6
1ElementHandle bodyHandle = page.evaluate("document.body"); 2String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello")); 3bodyHandle.dispose(); 4
1body_handle = await page.evaluate("document.body") 2html = await page.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"]) 3await body_handle.dispose() 4
1body_handle = page.evaluate("document.body") 2html = page.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"]) 3body_handle.dispose() 4
1var bodyHandle = await page.EvaluateAsync("document.body"); 2var html = await page.EvaluateAsync<string>("([body, suffix]) => body.innerHTML + suffix", new object [] { bodyHandle, "hello" }); 3await bodyHandle.DisposeAsync(); 4

param: Page.evaluate.expression = %%-evaluate-expression-%%

  • since: v1.8

param: Page.evaluate.expression = %%-js-evaluate-pagefunction-%%

  • since: v1.8

param: Page.evaluate.arg

  • since: v1.8
  • arg ?<[EvaluationArgument]>

Optional argument to pass to [param: expression].

async method: Page.evaluateHandle

  • since: v1.8
  • returns: <[JSHandle]>

Returns the value of the [param: expression] invocation as a [JSHandle].

The only difference between [method: Page.evaluate] and [method: Page.evaluateHandle] is that [method: Page.evaluateHandle] returns [JSHandle].

If the function passed to the [method: Page.evaluateHandle] returns a [Promise], then [method: Page.evaluateHandle] would wait for the promise to resolve and return its value.

Usage

1// Handle for the window object. 2const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window)); 3
1// Handle for the window object. 2JSHandle aWindowHandle = page.evaluateHandle("() => Promise.resolve(window)"); 3
1a_window_handle = await page.evaluate_handle("Promise.resolve(window)") 2a_window_handle # handle for the window object. 3
1a_window_handle = page.evaluate_handle("Promise.resolve(window)") 2a_window_handle # handle for the window object. 3
1// Handle for the window object. 2var aWindowHandle = await page.EvaluateHandleAsync("() => Promise.resolve(window)"); 3

A string can also be passed in instead of a function:

1const aHandle = await page.evaluateHandle('document'); // Handle for the 'document' 2
1JSHandle aHandle = page.evaluateHandle("document"); // Handle for the "document". 2
1a_handle = await page.evaluate_handle("document") # handle for the "document" 2
1a_handle = page.evaluate_handle("document") # handle for the "document" 2
1var docHandle = await page.EvaluateHandleAsync("document"); // Handle for the `document` 2

[JSHandle] instances can be passed as an argument to the [method: Page.evaluateHandle]:

1const aHandle = await page.evaluateHandle(() => document.body); 2const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle); 3console.log(await resultHandle.jsonValue()); 4await resultHandle.dispose(); 5
1JSHandle aHandle = page.evaluateHandle("() => document.body"); 2JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello")); 3System.out.println(resultHandle.jsonValue()); 4resultHandle.dispose(); 5
1a_handle = await page.evaluate_handle("document.body") 2result_handle = await page.evaluate_handle("body => body.innerHTML", a_handle) 3print(await result_handle.json_value()) 4await result_handle.dispose() 5
1a_handle = page.evaluate_handle("document.body") 2result_handle = page.evaluate_handle("body => body.innerHTML", a_handle) 3print(result_handle.json_value()) 4result_handle.dispose() 5
1var handle = await page.EvaluateHandleAsync("() => document.body"); 2var resultHandle = await page.EvaluateHandleAsync("([body, suffix]) => body.innerHTML + suffix", new object[] { handle, "hello" }); 3Console.WriteLine(await resultHandle.JsonValueAsync<string>()); 4await resultHandle.DisposeAsync(); 5

param: Page.evaluateHandle.expression = %%-evaluate-expression-%%

  • since: v1.8

param: Page.evaluateHandle.expression = %%-js-evaluate-pagefunction-%%

  • since: v1.8

param: Page.evaluateHandle.arg

  • since: v1.8
  • arg ?<[EvaluationArgument]>

Optional argument to pass to [param: expression].

async method: Page.exposeBinding

  • since: v1.8

The method adds a function called [param: name] on the window object of every frame in this 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.

The first argument of the [param: callback] function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

See [method: BrowserContext.exposeBinding] for the context-wide version.

:::note Functions installed via [method: Page.exposeBinding] survive navigations. :::

Usage

An example of exposing page URL to all frames in a page:

1const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. 2 3(async () => { 4 const browser = await webkit.launch({ headless: false }); 5 const context = await browser.newContext(); 6 const page = await context.newPage(); 7 await page.exposeBinding('pageURL', ({ page }) => page.url()); 8 await page.setContent(` 9 <script> 10 async function onClick() { 11 document.querySelector('div').textContent = await window.pageURL(); 12 } 13 </script> 14 <button onclick="onClick()">Click me</button> 15 <div></div> 16 `); 17 await page.click('button'); 18})(); 19
1import com.microsoft.playwright.*; 2 3public class Example { 4 public static void main(String[] args) { 5 try (Playwright playwright = Playwright.create()) { 6 BrowserType webkit = playwright.webkit(); 7 Browser browser = webkit.launch({ headless: false }); 8 BrowserContext context = browser.newContext(); 9 Page page = context.newPage(); 10 page.exposeBinding("pageURL", (source, args) -> source.page().url()); 11 page.setContent("<script>\n" + 12 " async function onClick() {\n" + 13 " document.querySelector('div').textContent = await window.pageURL();\n" + 14 " }\n" + 15 "</script>\n" + 16 "<button onclick=\"onClick()\">Click me</button>\n" + 17 "<div></div>"); 18 page.click("button"); 19 } 20 } 21} 22
1import asyncio 2from playwright.async_api import async_playwright, Playwright 3 4async def run(playwright: Playwright): 5 webkit = playwright.webkit 6 browser = await webkit.launch(headless=false) 7 context = await browser.new_context() 8 page = await context.new_page() 9 await page.expose_binding("pageURL", lambda source: source["page"].url) 10 await page.set_content(""" 11 <script> 12 async function onClick() { 13 document.querySelector('div').textContent = await window.pageURL(); 14 } 15 </script> 16 <button onclick="onClick()">Click me</button> 17 <div></div> 18 """) 19 await page.click("button") 20 21async def main(): 22 async with async_playwright() as playwright: 23 await run(playwright) 24asyncio.run(main()) 25
1from playwright.sync_api import sync_playwright, Playwright 2 3def run(playwright: Playwright): 4 webkit = playwright.webkit 5 browser = webkit.launch(headless=false) 6 context = browser.new_context() 7 page = context.new_page() 8 page.expose_binding("pageURL", lambda source: source["page"].url) 9 page.set_content(""" 10 <script> 11 async function onClick() { 12 document.querySelector('div').textContent = await window.pageURL(); 13 } 14 </script> 15 <button onclick="onClick()">Click me</button> 16 <div></div> 17 """) 18 page.click("button") 19 20with sync_playwright() as playwright: 21 run(playwright) 22
1using Microsoft.Playwright; 2using System.Threading.Tasks; 3 4class PageExamples 5{ 6 public static async Task Main() 7 { 8 using var playwright = await Playwright.CreateAsync(); 9 await using var browser = await playwright.Webkit.LaunchAsync(new() 10 { 11 Headless = false, 12 }); 13 var page = await browser.NewPageAsync(); 14 15 await page.ExposeBindingAsync("pageUrl", (source) => source.Page.Url); 16 await page.SetContentAsync("<script>\n" + 17 " async function onClick() {\n" + 18 " document.querySelector('div').textContent = await window.pageURL();\n" + 19 " }\n" + 20 "</script>\n" + 21 "<button onclick=\"onClick()\">Click me</button>\n" + 22 "<div></div>"); 23 24 await page.ClickAsync("button"); 25 } 26} 27

An example of passing an element handle:

1await page.exposeBinding('clicked', async (source, element) => { 2 console.log(await element.textContent()); 3}, { handle: true }); 4await page.setContent(` 5 <script> 6 document.addEventListener('click', event => window.clicked(event.target)); 7 </script> 8 <div>Click me</div> 9 <div>Or click me</div> 10`); 11
1page.exposeBinding("clicked", (source, args) -> { 2 ElementHandle element = (ElementHandle) args[0]; 3 System.out.println(element.textContent()); 4 return null; 5}, new Page.ExposeBindingOptions().setHandle(true)); 6page.setContent("" + 7 "<script>\n" + 8 " document.addEventListener('click', event => window.clicked(event.target));\n" + 9 "</script>\n" + 10 "<div>Click me</div>\n" + 11 "<div>Or click me</div>\n"); 12
1async def print(source, element): 2 print(await element.text_content()) 3 4await page.expose_binding("clicked", print, handle=true) 5await page.set_content(""" 6 <script> 7 document.addEventListener('click', event => window.clicked(event.target)); 8 </script> 9 <div>Click me</div> 10 <div>Or click me</div> 11""") 12
1def print(source, element): 2 print(element.text_content()) 3 4page.expose_binding("clicked", print, handle=true) 5page.set_content(""" 6 <script> 7 document.addEventListener('click', event => window.clicked(event.target)); 8 </script> 9 <div>Click me</div> 10 <div>Or click me</div> 11""") 12
1var result = new TaskCompletionSource<string>(); 2await page.ExposeBindingAsync("clicked", async (BindingSource _, IJSHandle t) => 3{ 4 return result.TrySetResult(await t.AsElement().TextContentAsync()); 5}); 6 7await page.SetContentAsync("<script>\n" + 8 " document.addEventListener('click', event => window.clicked(event.target));\n" + 9 "</script>\n" + 10 "<div>Click me</div>\n" + 11 "<div>Or click me</div>\n"); 12 13await page.ClickAsync("div"); 14Console.WriteLine(await result.Task); 15

param: Page.exposeBinding.name

  • since: v1.8
  • name <[string]>

Name of the function on the window object.

param: Page.exposeBinding.callback

  • since: v1.8
  • callback <[function]>

Callback function that will be called in the Playwright's context.

option: Page.exposeBinding.handle

  • since: v1.8
  • 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

  • since: v1.8

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. :::

Usage

An example of adding a sha256 function to the page:

1const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. 2const crypto = require('crypto'); 3 4(async () => { 5 const browser = await webkit.launch({ headless: false }); 6 const page = await browser.newPage(); 7 await page.exposeFunction('sha256', text => 8 crypto.createHash('sha256').update(text).digest('hex'), 9 ); 10 await page.setContent(` 11 <script> 12 async function onClick() { 13 document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT'); 14 } 15 </script> 16 <button onclick="onClick()">Click me</button> 17 <div></div> 18 `); 19 await page.click('button'); 20})(); 21
1import com.microsoft.playwright.*; 2 3import java.nio.charset.StandardCharsets; 4import java.security.MessageDigest; 5import java.security.NoSuchAlgorithmException; 6import java.util.Base64; 7 8public class Example { 9 public static void main(String[] args) { 10 try (Playwright playwright = Playwright.create()) { 11 BrowserType webkit = playwright.webkit(); 12 Browser browser = webkit.launch({ headless: false }); 13 Page page = browser.newPage(); 14 page.exposeFunction("sha256", args -> { 15 String text = (String) args[0]; 16 MessageDigest crypto; 17 try { 18 crypto = MessageDigest.getInstance("SHA-256"); 19 } catch (NoSuchAlgorithmException e) { 20 return null; 21 } 22 byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8)); 23 return Base64.getEncoder().encodeToString(token); 24 }); 25 page.setContent("<script>\n" + 26 " async function onClick() {\n" + 27 " document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" + 28 " }\n" + 29 "</script>\n" + 30 "<button onclick=\"onClick()\">Click me</button>\n" + 31 "<div></div>\n"); 32 page.click("button"); 33 } 34 } 35} 36
1import asyncio 2import hashlib 3from playwright.async_api import async_playwright, Playwright 4 5def sha256(text): 6 m = hashlib.sha256() 7 m.update(bytes(text, "utf8")) 8 return m.hexdigest() 9 10 11async def run(playwright: Playwright): 12 webkit = playwright.webkit 13 browser = await webkit.launch(headless=False) 14 page = await browser.new_page() 15 await page.expose_function("sha256", sha256) 16 await page.set_content(""" 17 <script> 18 async function onClick() { 19 document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT'); 20 } 21 </script> 22 <button onclick="onClick()">Click me</button> 23 <div></div> 24 """) 25 await page.click("button") 26 27async def main(): 28 async with async_playwright() as playwright: 29 await run(playwright) 30asyncio.run(main()) 31
1import hashlib 2from playwright.sync_api import sync_playwright, Playwright 3 4def sha256(text): 5 m = hashlib.sha256() 6 m.update(bytes(text, "utf8")) 7 return m.hexdigest() 8 9 10def run(playwright: Playwright): 11 webkit = playwright.webkit 12 browser = webkit.launch(headless=False) 13 page = browser.new_page() 14 page.expose_function("sha256", sha256) 15 page.set_content(""" 16 <script> 17 async function onClick() { 18 document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT'); 19 } 20 </script> 21 <button onclick="onClick()">Click me</button> 22 <div></div> 23 """) 24 page.click("button") 25 26with sync_playwright() as playwright: 27 run(playwright) 28
1using Microsoft.Playwright; 2using System; 3using System.Security.Cryptography; 4using System.Threading.Tasks; 5 6class PageExamples 7{ 8 public static async Task Main() 9 { 10 using var playwright = await Playwright.CreateAsync(); 11 await using var browser = await playwright.Webkit.LaunchAsync(new() 12 { 13 Headless = false 14 }); 15 var page = await browser.NewPageAsync(); 16 17 await page.ExposeFunctionAsync("sha256", (string input) => 18 { 19 return Convert.ToBase64String( 20 SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input))); 21 }); 22 23 await page.SetContentAsync("<script>\n" + 24 " async function onClick() {\n" + 25 " document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" + 26 " }\n" + 27 "</script>\n" + 28 "<button onclick=\"onClick()\">Click me</button>\n" + 29 "<div></div>"); 30 31 await page.ClickAsync("button"); 32 Console.WriteLine(await page.TextContentAsync("div")); 33 } 34} 35

param: Page.exposeFunction.name

  • since: v1.8
  • name <[string]>

Name of the function on the window object

param: Page.exposeFunction.callback

  • since: v1.8
  • callback <[function]>

Callback function which will be called in Playwright's context.

async method: Page.fill

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.fill] instead. Read more about locators.

This method waits for an element matching [param: selector], waits for actionability 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 <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.

To send fine-grained keyboard events, use [method: Locator.pressSequentially].

param: Page.fill.selector = %%-input-selector-%%

  • since: v1.8

param: Page.fill.value

  • since: v1.8
  • value <[string]>

Value to fill for the <input>, <textarea> or [contenteditable] element.

option: Page.fill.force = %%-input-force-%%

  • since: v1.13

option: Page.fill.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.fill.strict = %%-input-strict-%%

  • since: v1.14

option: Page.fill.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.fill.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.focus

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.focus] instead. Read more about locators.

This method fetches an element with [param: selector] and focuses it. If there's no element matching [param: selector], the method waits until a matching element appears in the DOM.

param: Page.focus.selector = %%-input-selector-%%

  • since: v1.8

option: Page.focus.strict = %%-input-strict-%%

  • since: v1.14

option: Page.focus.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.focus.timeout = %%-input-timeout-js-%%

  • since: v1.8

method: Page.frame

  • since: v1.8
  • returns: <[null]|[Frame]>

Returns frame matching the specified criteria. Either name or url must be specified.

Usage

1const frame = page.frame('frame-name'); 2
1Frame frame = page.frame("frame-name"); 2
1frame = page.frame(name="frame-name") 2
1var frame = page.Frame("frame-name"); 2
1const frame = page.frame({ url: /.*domain.*/ }); 2
1Frame frame = page.frameByUrl(Pattern.compile(".*domain.*"); 2
1frame = page.frame(url=r".*domain.*") 2
1var frame = page.FrameByUrl(".*domain.*"); 2

param: Page.frame.frameSelector

  • since: v1.8
  • langs: js
  • frameSelector <[string]|[Object]>
    • name ?<[string]> Frame name specified in the iframe's name attribute. Optional.
    • url ?<[string]|[RegExp]|[function]([URL]):[boolean]> A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object. Optional.

Frame name or other frame lookup options.

param: Page.frame.name

  • since: v1.9
  • langs: csharp, java
  • name <[string]>

Frame name specified in the iframe's name attribute.

option: Page.frame.name

  • since: v1.8
  • langs: python
  • name ?<[string]>

Frame name specified in the iframe's name attribute. Optional.

option: Page.frame.url

  • since: v1.8
  • langs: python
  • url ?<[string]|[RegExp]|[function]([URL]):[boolean]>

A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object. Optional.

method: Page.frameByUrl

  • since: v1.9
  • langs: csharp, java
  • returns: <[null]|[Frame]>

Returns frame with matching URL.

param: Page.frameByUrl.url

  • since: v1.9
  • langs: csharp, java
  • url <[string]|[RegExp]|[function]([URL]):[boolean]>

A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object.

method: Page.frameLocator

  • since: v1.17
  • returns: <[FrameLocator]>

When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.

Usage

Following snippet locates element with text "Submit" in the iframe with id my-frame, like <iframe id="my-frame">:

1const locator = page.frameLocator('#my-iframe').getByText('Submit'); 2await locator.click(); 3
1Locator locator = page.frameLocator("#my-iframe").getByText("Submit"); 2locator.click(); 3
1locator = page.frame_locator("#my-iframe").get_by_text("Submit") 2await locator.click() 3
1locator = page.frame_locator("#my-iframe").get_by_text("Submit") 2locator.click() 3
1var locator = page.FrameLocator("#my-iframe").GetByText("Submit"); 2await locator.ClickAsync(); 3

param: Page.frameLocator.selector = %%-find-selector-%%

  • since: v1.17

method: Page.frames

  • since: v1.8
  • returns: <[Array]<[Frame]>>

An array of all frames attached to the page.

async method: Page.getAttribute

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.getAttribute] instead. Read more about locators.
  • returns: <[null]|[string]>

Returns element attribute value.

param: Page.getAttribute.selector = %%-input-selector-%%

  • since: v1.8

param: Page.getAttribute.name

  • since: v1.8
  • name <[string]>

Attribute name to get the value for.

option: Page.getAttribute.strict = %%-input-strict-%%

  • since: v1.14

option: Page.getAttribute.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.getAttribute.timeout = %%-input-timeout-js-%%

  • since: v1.8

method: Page.getByAltText

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-alt-text-%%

param: Page.getByAltText.text = %%-locator-get-by-text-text-%%

option: Page.getByAltText.exact = %%-locator-get-by-text-exact-%%

method: Page.getByLabel

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-label-text-%%

param: Page.getByLabel.text = %%-locator-get-by-text-text-%%

option: Page.getByLabel.exact = %%-locator-get-by-text-exact-%%

method: Page.getByPlaceholder

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-placeholder-text-%%

param: Page.getByPlaceholder.text = %%-locator-get-by-text-text-%%

option: Page.getByPlaceholder.exact = %%-locator-get-by-text-exact-%%

method: Page.getByRole

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-role-%%

param: Page.getByRole.role = %%-locator-get-by-role-role-%%

option: Page.getByRole.-inline- = %%-locator-get-by-role-option-list-v1.27-%%

  • since: v1.27

option: Page.getByRole.exact = %%-locator-get-by-role-option-exact-%%

method: Page.getByTestId

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-test-id-%%

param: Page.getByTestId.testId = %%-locator-get-by-test-id-test-id-%%

  • since: v1.27

method: Page.getByText

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-text-%%

param: Page.getByText.text = %%-locator-get-by-text-text-%%

option: Page.getByText.exact = %%-locator-get-by-text-exact-%%

method: Page.getByTitle

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-title-%%

param: Page.getByTitle.text = %%-locator-get-by-text-text-%%

option: Page.getByTitle.exact = %%-locator-get-by-text-exact-%%

async method: Page.goBack

  • since: v1.8
  • returns: <[null]|[Response]>

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns null.

Navigate to the previous page in history.

option: Page.goBack.waitUntil = %%-navigation-wait-until-%%

  • since: v1.8

option: Page.goBack.timeout = %%-navigation-timeout-%%

  • since: v1.8

option: Page.goBack.timeout = %%-navigation-timeout-js-%%

  • since: v1.8

async method: Page.goForward

  • since: v1.8
  • returns: <[null]|[Response]>

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns null.

Navigate to the next page in history.

option: Page.goForward.waitUntil = %%-navigation-wait-until-%%

  • since: v1.8

option: Page.goForward.timeout = %%-navigation-timeout-%%

  • since: v1.8

option: Page.goForward.timeout = %%-navigation-timeout-js-%%

  • since: v1.8

async method: Page.goto

  • since: v1.8
  • langs:
    • alias-java: navigate
  • returns: <[null]|[Response]>

Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.

The method will throw an error if:

  • there's an SSL error (e.g. in case of self-signed certificates).
  • target URL is invalid.
  • the [option: timeout] is exceeded during navigation.
  • the remote server does not respond or is unreachable.
  • the main resource failed to load.

The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [method: Response.status].

:::note The method either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null. :::

:::note Headless mode doesn't support navigation to a PDF document. See the upstream issue. :::

param: Page.goto.url

  • since: v1.8
  • url <[string]>

URL to navigate page to. The url should include scheme, e.g. https://. When a [option: baseURL] via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

option: Page.goto.waitUntil = %%-navigation-wait-until-%%

  • since: v1.8

option: Page.goto.timeout = %%-navigation-timeout-%%

  • since: v1.8

option: Page.goto.timeout = %%-navigation-timeout-js-%%

  • since: v1.8

option: Page.goto.referer

  • since: v1.8
  • referer <[string]>

Referer header value. If provided it will take preference over the referer header value set by [method: Page.setExtraHTTPHeaders].

async method: Page.hover

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.hover] instead. Read more about locators.

This method hovers over an element matching [param: selector] by performing the following steps:

  1. Find an element matching [param: selector]. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to hover over the center of the element, or the specified [option: position].
  5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

param: Page.hover.selector = %%-input-selector-%%

  • since: v1.8

option: Page.hover.force = %%-input-force-%%

  • since: v1.8

option: Page.hover.modifiers = %%-input-modifiers-%%

  • since: v1.8

option: Page.hover.position = %%-input-position-%%

  • since: v1.8

option: Page.hover.strict = %%-input-strict-%%

  • since: v1.14

option: Page.hover.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.hover.timeout = %%-input-timeout-js-%%

  • since: v1.8

option: Page.hover.trial = %%-input-trial-%%

  • since: v1.11

option: Page.hover.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.28

async method: Page.innerHTML

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.innerHTML] instead. Read more about locators.
  • returns: <[string]>

Returns element.innerHTML.

param: Page.innerHTML.selector = %%-input-selector-%%

  • since: v1.8

option: Page.innerHTML.strict = %%-input-strict-%%

  • since: v1.14

option: Page.innerHTML.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.innerHTML.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.innerText

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.innerText] instead. Read more about locators.
  • returns: <[string]>

Returns element.innerText.

param: Page.innerText.selector = %%-input-selector-%%

  • since: v1.8

option: Page.innerText.strict = %%-input-strict-%%

  • since: v1.14

option: Page.innerText.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.innerText.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.inputValue

  • since: v1.13
  • discouraged: Use locator-based [method: Locator.inputValue] instead. Read more about locators.
  • returns: <[string]>

Returns input.value for the selected <input> or <textarea> or <select> element.

Throws for non-input elements. However, if the element is inside the <label> element that has an associated control, returns the value of the control.

param: Page.inputValue.selector = %%-input-selector-%%

  • since: v1.13

option: Page.inputValue.strict = %%-input-strict-%%

  • since: v1.14

option: Page.inputValue.timeout = %%-input-timeout-%%

  • since: v1.13

option: Page.inputValue.timeout = %%-input-timeout-js-%%

  • since: v1.13

async method: Page.isChecked

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.isChecked] instead. Read more about locators.
  • returns: <[boolean]>

Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

param: Page.isChecked.selector = %%-input-selector-%%

  • since: v1.8

option: Page.isChecked.strict = %%-input-strict-%%

  • since: v1.14

option: Page.isChecked.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.isChecked.timeout = %%-input-timeout-js-%%

  • since: v1.8

method: Page.isClosed

  • since: v1.8
  • returns: <[boolean]>

Indicates that the page has been closed.

async method: Page.isDisabled

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.isDisabled] instead. Read more about locators.
  • returns: <[boolean]>

Returns whether the element is disabled, the opposite of enabled.

param: Page.isDisabled.selector = %%-input-selector-%%

  • since: v1.8

option: Page.isDisabled.strict = %%-input-strict-%%

  • since: v1.14

option: Page.isDisabled.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.isDisabled.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.isEditable

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.isEditable] instead. Read more about locators.
  • returns: <[boolean]>

Returns whether the element is editable.

param: Page.isEditable.selector = %%-input-selector-%%

  • since: v1.8

option: Page.isEditable.strict = %%-input-strict-%%

  • since: v1.14

option: Page.isEditable.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.isEditable.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.isEnabled

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.isEnabled] instead. Read more about locators.
  • returns: <[boolean]>

Returns whether the element is enabled.

param: Page.isEnabled.selector = %%-input-selector-%%

  • since: v1.8

option: Page.isEnabled.strict = %%-input-strict-%%

  • since: v1.14

option: Page.isEnabled.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.isEnabled.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.isHidden

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.isHidden] instead. Read more about locators.
  • returns: <[boolean]>

Returns whether the element is hidden, the opposite of visible. [option: selector] that does not match any elements is considered hidden.

param: Page.isHidden.selector = %%-input-selector-%%

  • since: v1.8

option: Page.isHidden.strict = %%-input-strict-%%

  • since: v1.14

option: Page.isHidden.timeout

  • since: v1.8
  • deprecated: This option is ignored. [method: Page.isHidden] does not wait for the element to become hidden and returns immediately.
  • timeout <[float]>

async method: Page.isVisible

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.isVisible] instead. Read more about locators.
  • returns: <[boolean]>

Returns whether the element is visible. [option: selector] that does not match any elements is considered not visible.

param: Page.isVisible.selector = %%-input-selector-%%

  • since: v1.8

option: Page.isVisible.strict = %%-input-strict-%%

  • since: v1.14

option: Page.isVisible.timeout

  • since: v1.8
  • deprecated: This option is ignored. [method: Page.isVisible] does not wait for the element to become visible and returns immediately.
  • timeout <[float]>

property: Page.keyboard

  • since: v1.8
  • type: <[Keyboard]>

method: Page.locator

  • since: v1.14
  • returns: <[Locator]>

%%-template-locator-root-locator-%%

param: Page.locator.selector = %%-find-selector-%%

  • since: v1.14

option: Page.locator.-inline- = %%-locator-options-list-v1.14-%%

  • since: v1.14

option: Page.locator.hasNot = %%-locator-option-has-not-%%

  • since: v1.33

option: Page.locator.hasNotText = %%-locator-option-has-not-text-%%

  • since: v1.33

method: Page.mainFrame

  • since: v1.8
  • returns: <[Frame]>

The page's main frame. Page is guaranteed to have a main frame which persists during navigations.

property: Page.mouse

  • since: v1.8
  • type: <[Mouse]>

method: Page.onceDialog

  • since: v1.10
  • langs: java

Adds one-off [Dialog] handler. The handler will be removed immediately after next [Dialog] is created.

1page.onceDialog(dialog -> { 2 dialog.accept("foo"); 3}); 4 5// prints 'foo' 6System.out.println(page.evaluate("prompt('Enter string:')")); 7 8// prints 'null' as the dialog will be auto-dismissed because there are no handlers. 9System.out.println(page.evaluate("prompt('Enter string:')")); 10

This code above is equivalent to:

1Consumer<Dialog> handler = new Consumer<Dialog>() { 2 @Override 3 public void accept(Dialog dialog) { 4 dialog.accept("foo"); 5 page.offDialog(this); 6 } 7}; 8page.onDialog(handler); 9 10// prints 'foo' 11System.out.println(page.evaluate("prompt('Enter string:')")); 12 13// prints 'null' as the dialog will be auto-dismissed because there are no handlers. 14System.out.println(page.evaluate("prompt('Enter string:')")); 15

param: Page.onceDialog.handler

  • since: v1.10
  • handler <[function]([Dialog])>

Receives the [Dialog] object, it must either [method: Dialog.accept] or [method: Dialog.dismiss] the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

async method: Page.opener

  • since: v1.8
  • returns: <[null]|[Page]>

Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.

async method: Page.pause

  • since: v1.9

Pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to call playwright.resume() in the DevTools console.

User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.

:::note This method requires Playwright to be started in a headed mode, with a falsy [option: headless] value in the [method: BrowserType.launch]. :::

async method: Page.pdf

  • since: v1.8
  • returns: <[Buffer]>

Returns the PDF buffer.

:::note Generating a pdf is currently only supported in Chromium headless. :::

page.pdf() generates a pdf of the page with print css media. To generate a pdf with screen media, call [method: Page.emulateMedia] before calling page.pdf():

:::note By default, page.pdf() generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust property to force rendering of exact colors. :::

Usage

1// Generates a PDF with 'screen' media type. 2await page.emulateMedia({ media: 'screen' }); 3await page.pdf({ path: 'page.pdf' }); 4
1// Generates a PDF with "screen" media type. 2page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN)); 3page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf"))); 4
1# generates a pdf with "screen" media type. 2await page.emulate_media(media="screen") 3await page.pdf(path="page.pdf") 4
1# generates a pdf with "screen" media type. 2page.emulate_media(media="screen") 3page.pdf(path="page.pdf") 4
1// Generates a PDF with 'screen' media type 2await page.EmulateMediaAsync(new() { Media = Media.Screen }); 3await page.PdfAsync(new() { Path = "page.pdf" }); 4

The [option: width], [option: height], and [option: margin] options accept values labeled with units. Unlabeled values are treated as pixels.

A few examples:

  • page.pdf({width: 100}) - prints with width set to 100 pixels
  • page.pdf({width: '100px'}) - prints with width set to 100 pixels
  • page.pdf({width: '10cm'}) - prints with width set to 10 centimeters.

All possible units are:

  • px - pixel
  • in - inch
  • cm - centimeter
  • mm - millimeter

The [option: format] options are:

  • Letter: 8.5in x 11in
  • Legal: 8.5in x 14in
  • Tabloid: 11in x 17in
  • Ledger: 17in x 11in
  • A0: 33.1in x 46.8in
  • A1: 23.4in x 33.1in
  • A2: 16.54in x 23.4in
  • A3: 11.7in x 16.54in
  • A4: 8.27in x 11.7in
  • A5: 5.83in x 8.27in
  • A6: 4.13in x 5.83in

:::note [option: headerTemplate] and [option: footerTemplate] markup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates. :::

option: Page.pdf.path

  • since: v1.8
  • path <[path]>

The file path to save the PDF to. If [option: path] is a relative path, then it is resolved relative to the current working directory. If no path is provided, the PDF won't be saved to the disk.

option: Page.pdf.scale

  • since: v1.8
  • scale <[float]>

Scale of the webpage rendering. Defaults to 1. Scale amount must be between 0.1 and 2.

option: Page.pdf.displayHeaderFooter

  • since: v1.8
  • displayHeaderFooter <[boolean]>

Display header and footer. Defaults to false.

option: Page.pdf.headerTemplate

  • since: v1.8
  • headerTemplate <[string]>

HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them:

  • 'date' formatted print date
  • 'title' document title
  • 'url' document location
  • 'pageNumber' current page number
  • 'totalPages' total pages in the document

option: Page.pdf.footerTemplate

  • since: v1.8
  • footerTemplate <[string]>

HTML template for the print footer. Should use the same format as the [option: headerTemplate].

option: Page.pdf.printBackground

  • since: v1.8
  • printBackground <[boolean]>

Print background graphics. Defaults to false.

option: Page.pdf.landscape

  • since: v1.8
  • landscape <[boolean]>

Paper orientation. Defaults to false.

option: Page.pdf.pageRanges

  • since: v1.8
  • pageRanges <[string]>

Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.

option: Page.pdf.format

  • since: v1.8
  • format <[string]>

Paper format. If set, takes priority over [option: width] or [option: height] options. Defaults to 'Letter'.

option: Page.pdf.width

  • since: v1.8
  • langs: js, python
  • width <[string]|[float]>

Paper width, accepts values labeled with units.

option: Page.pdf.width

  • since: v1.8
  • langs: csharp, java
  • width <[string]>

Paper width, accepts values labeled with units.

option: Page.pdf.height

  • since: v1.8
  • langs: js, python
  • height <[string]|[float]>

Paper height, accepts values labeled with units.

option: Page.pdf.height

  • since: v1.8
  • langs: csharp, java
  • height <[string]>

Paper height, accepts values labeled with units.

option: Page.pdf.margin

  • since: v1.8
  • langs: js, python
  • margin <[Object]>
    • top ?<[string]|[float]> Top margin, accepts values labeled with units. Defaults to 0.
    • right ?<[string]|[float]> Right margin, accepts values labeled with units. Defaults to 0.
    • bottom ?<[string]|[float]> Bottom margin, accepts values labeled with units. Defaults to 0.
    • left ?<[string]|[float]> Left margin, accepts values labeled with units. Defaults to 0.

Paper margins, defaults to none.

option: Page.pdf.margin

  • since: v1.8
  • langs: csharp, java
  • margin <[Object]>
    • top ?<[string]> Top margin, accepts values labeled with units. Defaults to 0.
    • right ?<[string]> Right margin, accepts values labeled with units. Defaults to 0.
    • bottom ?<[string]> Bottom margin, accepts values labeled with units. Defaults to 0.
    • left ?<[string]> Left margin, accepts values labeled with units. Defaults to 0.

Paper margins, defaults to none.

option: Page.pdf.preferCSSPageSize

  • since: v1.8
  • preferCSSPageSize <[boolean]>

Give any CSS @page size declared in the page priority over what is declared in [option: width] and [option: height] or [option: format] options. Defaults to false, which will scale the content to fit the paper size.

async method: Page.press

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.press] instead. Read more about locators.

Focuses the element, and then uses [method: Keyboard.down] and [method: Keyboard.up].

[param: key] can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the [param: key] values can be found here. Examples of the keys are:

F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft.

Holding down Shift will type the text that corresponds to the [param: key] in the upper case.

If [param: key] is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

Shortcuts such as key: "Control+o" or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

Usage

1const page = await browser.newPage(); 2await page.goto('https://keycode.info'); 3await page.press('body', 'A'); 4await page.screenshot({ path: 'A.png' }); 5await page.press('body', 'ArrowLeft'); 6await page.screenshot({ path: 'ArrowLeft.png' }); 7await page.press('body', 'Shift+O'); 8await page.screenshot({ path: 'O.png' }); 9await browser.close(); 10
1Page page = browser.newPage(); 2page.navigate("https://keycode.info"); 3page.press("body", "A"); 4page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png"))); 5page.press("body", "ArrowLeft"); 6page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png" ))); 7page.press("body", "Shift+O"); 8page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png" ))); 9
1page = await browser.new_page() 2await page.goto("https://keycode.info") 3await page.press("body", "A") 4await page.screenshot(path="a.png") 5await page.press("body", "ArrowLeft") 6await page.screenshot(path="arrow_left.png") 7await page.press("body", "Shift+O") 8await page.screenshot(path="o.png") 9await browser.close() 10
1page = browser.new_page() 2page.goto("https://keycode.info") 3page.press("body", "A") 4page.screenshot(path="a.png") 5page.press("body", "ArrowLeft") 6page.screenshot(path="arrow_left.png") 7page.press("body", "Shift+O") 8page.screenshot(path="o.png") 9browser.close() 10
1var page = await browser.NewPageAsync(); 2await page.GotoAsync("https://keycode.info"); 3await page.PressAsync("body", "A"); 4await page.ScreenshotAsync(new() { Path = "A.png" }); 5await page.PressAsync("body", "ArrowLeft"); 6await page.ScreenshotAsync(new() { Path = "ArrowLeft.png" }); 7await page.PressAsync("body", "Shift+O"); 8await page.ScreenshotAsync(new() { Path = "O.png" }); 9

param: Page.press.selector = %%-input-selector-%%

  • since: v1.8

param: Page.press.key

  • since: v1.8
  • key <[string]>

Name of the key to press or a character to generate, such as ArrowLeft or a.

option: Page.press.delay

  • since: v1.8
  • delay <[float]>

Time to wait between keydown and keyup in milliseconds. Defaults to 0.

option: Page.press.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.press.strict = %%-input-strict-%%

  • since: v1.14

option: Page.press.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.press.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.querySelector

  • since: v1.9
  • discouraged: Use locator-based [method: Page.locator] instead. Read more about locators.
  • langs:
    • alias-python: query_selector
    • alias-js: $
  • 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. To wait for an element on the page, use [method: Locator.waitFor].

param: Page.querySelector.selector = %%-query-selector-%%

  • since: v1.9

option: Page.querySelector.strict = %%-input-strict-%%

  • since: v1.14

async method: Page.querySelectorAll

  • since: v1.9
  • discouraged: Use locator-based [method: Page.locator] instead. Read more about locators.
  • langs:
    • alias-python: query_selector_all
    • alias-js: $$
  • 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 [].

param: Page.querySelectorAll.selector = %%-query-selector-%%

  • since: v1.9

async method: Page.reload

  • since: v1.8
  • returns: <[null]|[Response]>

This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.

option: Page.reload.waitUntil = %%-navigation-wait-until-%%

  • since: v1.8

option: Page.reload.timeout = %%-navigation-timeout-%%

  • since: v1.8

option: Page.reload.timeout = %%-navigation-timeout-js-%%

  • since: v1.8

property: Page.request

  • since: v1.16
  • langs:
    • alias-csharp: APIRequest
  • type: <[APIRequestContext]>

API testing helper associated with this page. This method returns the same instance as [property: BrowserContext.request] on the page's context. See [property: BrowserContext.request] for more details.

async method: Page.route

  • since: v1.8

Routing provides the capability to modify network requests that are made by a page.

Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

:::note The handler will only be called for the first url if the response is a redirect. :::

:::note [method: Page.route] will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting [option: Browser.newContext.serviceWorkers] to 'block'. :::

Usage

An example of a naive handler that aborts all image requests:

1const page = await browser.newPage(); 2await page.route('**/*.{png,jpg,jpeg}', route => route.abort()); 3await page.goto('https://example.com'); 4await browser.close(); 5
1Page page = browser.newPage(); 2page.route("**/*.{png,jpg,jpeg}", route -> route.abort()); 3page.navigate("https://example.com"); 4browser.close(); 5
1page = await browser.new_page() 2await page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort()) 3await page.goto("https://example.com") 4await browser.close() 5
1page = browser.new_page() 2page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort()) 3page.goto("https://example.com") 4browser.close() 5
1var page = await browser.NewPageAsync(); 2await page.RouteAsync("**/*.{png,jpg,jpeg}", async r => await r.AbortAsync()); 3await page.GotoAsync("https://www.microsoft.com"); 4

or the same snippet using a regex pattern instead:

1const page = await browser.newPage(); 2await page.route(/(\.png$)|(\.jpg$)/, route => route.abort()); 3await page.goto('https://example.com'); 4await browser.close(); 5
1Page page = browser.newPage(); 2page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort()); 3page.navigate("https://example.com"); 4browser.close(); 5
1page = await browser.new_page() 2await page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort()) 3await page.goto("https://example.com") 4await browser.close() 5
1page = browser.new_page() 2page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort()) 3page.goto("https://example.com") 4browser.close() 5
1var page = await browser.NewPageAsync(); 2await page.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), async r => await r.AbortAsync()); 3await page.GotoAsync("https://www.microsoft.com"); 4

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

1await page.route('/api/**', route => { 2 if (route.request().postData().includes('my-string')) 3 route.fulfill({ body: 'mocked-data' }); 4 else 5 route.continue(); 6}); 7
1page.route("/api/**", route -> { 2 if (route.request().postData().contains("my-string")) 3 route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); 4 else 5 route.resume(); 6}); 7
1def handle_route(route): 2 if ("my-string" in route.request.post_data): 3 route.fulfill(body="mocked-data") 4 else: 5 route.continue_() 6await page.route("/api/**", handle_route) 7
1def handle_route(route): 2 if ("my-string" in route.request.post_data): 3 route.fulfill(body="mocked-data") 4 else: 5 route.continue_() 6page.route("/api/**", handle_route) 7
1await page.RouteAsync("/api/**", async r => 2{ 3 if (r.Request.PostData.Contains("my-string")) 4 await r.FulfillAsync(new() { Body = "mocked-data" }); 5 else 6 await r.ContinueAsync(); 7}); 8

Page routes take precedence over browser context routes (set up with [method: BrowserContext.route]) when request matches both handlers.

To remove a route with its handler you can use [method: Page.unroute].

:::note Enabling routing disables http cache. :::

param: Page.route.url

  • since: v1.8
  • url <[string]|[RegExp]|[function]([URL]):[boolean]>

A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a [option: baseURL] via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

param: Page.route.handler

  • since: v1.8
  • langs: js, python
  • handler <[function]([Route], [Request]): [Promise|any]>

handler function to route the request.

param: Page.route.handler

  • since: v1.8
  • langs: csharp, java
  • handler <[function]([Route])>

handler function to route the request.

option: Page.route.times

  • since: v1.15
  • times <[int]>

How often a route should be used. By default it will be used every time.

async method: Page.routeFromHAR

  • since: v1.23

If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.

Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting [option: Browser.newContext.serviceWorkers] to 'block'.

param: Page.routeFromHAR.har

  • since: v1.23
  • har <[path]>

Path to a HAR file with prerecorded network data. If path is a relative path, then it is resolved relative to the current working directory.

option: Page.routeFromHAR.notFound

  • since: v1.23
  • notFound ?<[HarNotFound]<"abort"|"fallback">>
  • If set to 'abort' any request not found in the HAR file will be aborted.
  • If set to 'fallback' missing requests will be sent to the network.

Defaults to abort.

option: Page.routeFromHAR.update

  • since: v1.23
  • update ?

If specified, updates the given HAR with the actual network information instead of serving from file. The file is written to disk when [method: BrowserContext.close] is called.

option: Page.routeFromHAR.url

  • since: v1.23
  • url <[string]|[RegExp]>

A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.

option: Page.routeFromHAR.updateMode

  • since: v1.32
  • updateMode <[HarMode]<"full"|"minimal">>

When set to minimal, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to full.

option: Page.routeFromHAR.updateContent

  • since: v1.32
  • updateContent <[RouteFromHarUpdateContentPolicy]<"embed"|"attach">>

Optional setting to control resource content management. If attach is specified, resources are persisted as separate files or entries in the ZIP archive. If embed is specified, content is stored inline the HAR file.

async method: Page.screenshot

  • since: v1.8
  • returns: <[Buffer]>

Returns the buffer with the captured screenshot.

option: Page.screenshot.-inline- = %%-screenshot-options-common-list-v1.8-%%

  • since: v1.8

option: Page.screenshot.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.screenshot.timeout = %%-input-timeout-js-%%

  • since: v1.8

option: Page.screenshot.fullPage = %%-screenshot-option-full-page-%%

  • since: v1.8

option: Page.screenshot.clip = %%-screenshot-option-clip-%%

  • since: v1.8

option: Page.screenshot.maskColor = %%-screenshot-option-mask-color-%%

  • since: v1.34

async method: Page.selectOption

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.selectOption] instead. Read more about locators.
  • returns: <[Array]<[string]>>

This method waits for an element matching [param: selector], waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

Returns the array of option values that have been successfully selected.

Triggers a change and input event once all the provided options have been selected.

Usage

1// Single selection matching the value or label 2page.selectOption('select#colors', 'blue'); 3 4// single selection matching the label 5page.selectOption('select#colors', { label: 'Blue' }); 6 7// multiple selection 8page.selectOption('select#colors', ['red', 'green', 'blue']); 9 10
1// Single selection matching the value or label 2page.selectOption("select#colors", "blue"); 3// single selection matching both the value and the label 4page.selectOption("select#colors", new SelectOption().setLabel("Blue")); 5// multiple selection 6page.selectOption("select#colors", new String[] {"red", "green", "blue"}); 7
1# Single selection matching the value or label 2await page.select_option("select#colors", "blue") 3# single selection matching the label 4await page.select_option("select#colors", label="blue") 5# multiple selection 6await page.select_option("select#colors", value=["red", "green", "blue"]) 7
1# Single selection matching the value or label 2page.select_option("select#colors", "blue") 3# single selection matching both the label 4page.select_option("select#colors", label="blue") 5# multiple selection 6page.select_option("select#colors", value=["red", "green", "blue"]) 7
1// Single selection matching the value or label 2await page.SelectOptionAsync("select#colors", new[] { "blue" }); 3// single selection matching both the value and the label 4await page.SelectOptionAsync("select#colors", new[] { new SelectOptionValue() { Label = "blue" } }); 5// multiple 6await page.SelectOptionAsync("select#colors", new[] { "red", "green", "blue" }); 7

param: Page.selectOption.selector = %%-input-selector-%%

  • since: v1.8

param: Page.selectOption.values = %%-select-options-values-%%

  • since: v1.8

option: Page.selectOption.force = %%-input-force-%%

  • since: v1.13

option: Page.selectOption.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.selectOption.strict = %%-input-strict-%%

  • since: v1.14

option: Page.selectOption.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.selectOption.timeout = %%-input-timeout-js-%%

  • since: v1.8

param: Page.selectOption.element = %%-python-select-options-element-%%

  • since: v1.8

param: Page.selectOption.index = %%-python-select-options-index-%%

  • since: v1.8

param: Page.selectOption.value = %%-python-select-options-value-%%

  • since: v1.8

param: Page.selectOption.label = %%-python-select-options-label-%%

  • since: v1.8

async method: Page.setChecked

  • since: v1.15
  • discouraged: Use locator-based [method: Locator.setChecked] instead. Read more about locators.

This method checks or unchecks an element matching [param: selector] by performing the following steps:

  1. Find an element matching [param: selector]. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  3. If the element already has the right checked state, this method returns immediately.
  4. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  5. Scroll the element into view if needed.
  6. Use [property: Page.mouse] to click in the center of the element.
  7. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  8. Ensure that the element is now checked or unchecked. If not, this method throws.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

param: Page.setChecked.selector = %%-input-selector-%%

  • since: v1.15

param: Page.setChecked.checked = %%-input-checked-%%

  • since: v1.15

option: Page.setChecked.force = %%-input-force-%%

  • since: v1.15

option: Page.setChecked.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.15

option: Page.setChecked.position = %%-input-position-%%

  • since: v1.15

option: Page.setChecked.strict = %%-input-strict-%%

  • since: v1.15

option: Page.setChecked.timeout = %%-input-timeout-%%

  • since: v1.15

option: Page.setChecked.timeout = %%-input-timeout-js-%%

  • since: v1.15

option: Page.setChecked.trial = %%-input-trial-%%

  • since: v1.15

async method: Page.setContent

  • since: v1.8

This method internally calls document.write(), inheriting all its specific characteristics and behaviors.

param: Page.setContent.html

  • since: v1.8
  • html <[string]>

HTML markup to assign to the page.

option: Page.setContent.timeout = %%-navigation-timeout-%%

  • since: v1.8

option: Page.setContent.timeout = %%-navigation-timeout-js-%%

  • since: v1.8

option: Page.setContent.waitUntil = %%-navigation-wait-until-%%

  • since: v1.8

method: Page.setDefaultNavigationTimeout

  • since: v1.8

This setting will change the default maximum navigation time for the following methods and related shortcuts:

  • [method: Page.goBack]
  • [method: Page.goForward]
  • [method: Page.goto]
  • [method: Page.reload]
  • [method: Page.setContent]
  • [method: Page.waitForNavigation]
  • [method: Page.waitForURL]

:::note [method: Page.setDefaultNavigationTimeout] takes priority over [method: Page.setDefaultTimeout], [method: BrowserContext.setDefaultTimeout] and [method: BrowserContext.setDefaultNavigationTimeout]. :::

param: Page.setDefaultNavigationTimeout.timeout

  • since: v1.8
  • timeout <[float]>

Maximum navigation time in milliseconds

method: Page.setDefaultTimeout

  • since: v1.8

This setting will change the default maximum time for all the methods accepting [param: timeout] option.

:::note [method: Page.setDefaultNavigationTimeout] takes priority over [method: Page.setDefaultTimeout]. :::

param: Page.setDefaultTimeout.timeout

  • since: v1.8
  • timeout <[float]>

Maximum time in milliseconds

async method: Page.setExtraHTTPHeaders

  • since: v1.8

The extra HTTP headers will be sent with every request the page initiates.

:::note [method: Page.setExtraHTTPHeaders] does not guarantee the order of headers in the outgoing requests. :::

param: Page.setExtraHTTPHeaders.headers

  • since: v1.8
  • headers <[Object]<[string], [string]>>

An object containing additional HTTP headers to be sent with every request. All header values must be strings.

async method: Page.setInputFiles

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.setInputFiles] instead. Read more about locators.

Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.

This method expects [param: selector] to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

param: Page.setInputFiles.selector = %%-input-selector-%%

  • since: v1.8

param: Page.setInputFiles.files = %%-input-files-%%

  • since: v1.8

option: Page.setInputFiles.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.setInputFiles.strict = %%-input-strict-%%

  • since: v1.14

option: Page.setInputFiles.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.setInputFiles.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.setViewportSize

  • since: v1.8

In the case of multiple pages in a single browser, each page can have its own viewport size. However, [method: Browser.newContext] allows to set viewport size (and more) for all pages in the context at once.

[method: Page.setViewportSize] will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page. [method: Page.setViewportSize] will also reset screen size, use [method: Browser.newContext] with screen and viewport parameters if you need better control of these properties.

Usage

1const page = await browser.newPage(); 2await page.setViewportSize({ 3 width: 640, 4 height: 480, 5}); 6await page.goto('https://example.com'); 7
1Page page = browser.newPage(); 2page.setViewportSize(640, 480); 3page.navigate("https://example.com"); 4
1page = await browser.new_page() 2await page.set_viewport_size({"width": 640, "height": 480}) 3await page.goto("https://example.com") 4
1page = browser.new_page() 2page.set_viewport_size({"width": 640, "height": 480}) 3page.goto("https://example.com") 4
1var page = await browser.NewPageAsync(); 2await page.SetViewportSizeAsync(640, 480); 3await page.GotoAsync("https://www.microsoft.com"); 4

param: Page.setViewportSize.viewportSize

  • since: v1.8
  • langs: js, python
  • viewportSize <[Object]>
    • width <[int]> page width in pixels.
    • height <[int]> page height in pixels.

param: Page.setViewportSize.width

  • since: v1.10
  • langs: csharp, java
  • width <[int]> page width in pixels.

param: Page.setViewportSize.height

  • since: v1.10
  • langs: csharp, java
  • height <[int]> page height in pixels.

async method: Page.tap

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.tap] instead. Read more about locators.

This method taps an element matching [param: selector] by performing the following steps:

  1. Find an element matching [param: selector]. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.touchscreen] to tap the center of the element, or the specified [option: position].
  5. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

:::note [method: Page.tap] the method will throw if [option: hasTouch] option of the browser context is false. :::

param: Page.tap.selector = %%-input-selector-%%

  • since: v1.8

option: Page.tap.force = %%-input-force-%%

  • since: v1.8

option: Page.tap.modifiers = %%-input-modifiers-%%

  • since: v1.8

option: Page.tap.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.tap.position = %%-input-position-%%

  • since: v1.8

option: Page.tap.strict = %%-input-strict-%%

  • since: v1.14

option: Page.tap.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.tap.timeout = %%-input-timeout-js-%%

  • since: v1.8

option: Page.tap.trial = %%-input-trial-%%

  • since: v1.11

async method: Page.textContent

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.textContent] instead. Read more about locators.
  • returns: <[null]|[string]>

Returns element.textContent.

param: Page.textContent.selector = %%-input-selector-%%

  • since: v1.8

option: Page.textContent.strict = %%-input-strict-%%

  • since: v1.14

option: Page.textContent.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.textContent.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.title

  • since: v1.8
  • returns: <[string]>

Returns the page's title.

property: Page.touchscreen

  • since: v1.8
  • type: <[Touchscreen]>

async method: Page.type

  • since: v1.8
  • deprecated: In most cases, you should use [method: Locator.fill] instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use [method: Locator.pressSequentially].

Sends a keydown, keypress/input, and keyup event for each character in the text. page.type can be used to send fine-grained keyboard events. To fill values in form fields, use [method: Page.fill].

To press a special key, like Control or ArrowDown, use [method: Keyboard.press].

Usage

param: Page.type.selector = %%-input-selector-%%

  • since: v1.8

param: Page.type.text

  • since: v1.8
  • text <[string]>

A text to type into a focused element.

option: Page.type.delay

  • since: v1.8
  • delay <[float]>

Time to wait between key presses in milliseconds. Defaults to 0.

option: Page.type.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.type.strict = %%-input-strict-%%

  • since: v1.14

option: Page.type.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.type.timeout = %%-input-timeout-js-%%

  • since: v1.8

async method: Page.uncheck

  • since: v1.8
  • discouraged: Use locator-based [method: Locator.uncheck] instead. Read more about locators.

This method unchecks an element matching [param: selector] by performing the following steps:

  1. Find an element matching [param: selector]. If there is none, wait until a matching element is attached to the DOM.
  2. Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
  3. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  4. Scroll the element into view if needed.
  5. Use [property: Page.mouse] to click in the center of the element.
  6. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  7. Ensure that the element is now unchecked. If not, this method throws.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

param: Page.uncheck.selector = %%-input-selector-%%

  • since: v1.8

option: Page.uncheck.force = %%-input-force-%%

  • since: v1.8

option: Page.uncheck.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.8

option: Page.uncheck.position = %%-input-position-%%

  • since: v1.11

option: Page.uncheck.strict = %%-input-strict-%%

  • since: v1.14

option: Page.uncheck.timeout = %%-input-timeout-%%

  • since: v1.8

option: Page.uncheck.timeout = %%-input-timeout-js-%%

  • since: v1.8

option: Page.uncheck.trial = %%-input-trial-%%

  • since: v1.11

async method: Page.unroute

  • since: v1.8

Removes a route created with [method: Page.route]. When [param: handler] is not specified, removes all routes for the [param: url].

param: Page.unroute.url

  • since: v1.8
  • url <[string]|[RegExp]|[function]([URL]):[boolean]>

A glob pattern, regex pattern or predicate receiving [URL] to match while routing.

param: Page.unroute.handler

  • since: v1.8
  • langs: js, python
  • handler ?<[function]([Route], [Request]): [Promise|any]>

Optional handler function to route the request.

param: Page.unroute.handler

  • since: v1.8
  • langs: csharp, java
  • handler ?<[function]([Route])>

Optional handler function to route the request.

method: Page.url

  • since: v1.8
  • returns: <[string]>

method: Page.video

  • since: v1.8
  • returns: <[null]|[Video]>

Video object associated with this page.

method: Page.viewportSize

  • since: v1.8
  • returns: <[null]|[Object]>
    • width <[int]> page width in pixels.
    • height <[int]> page height in pixels.

async method: Page.waitForClose

  • since: v1.11
  • langs: java
  • returns: <[Page]>

Performs action and waits for the Page to close.

option: Page.waitForClose.timeout = %%-wait-for-event-timeout-%%

  • since: v1.9

param: Page.waitForClose.callback = %%-java-wait-for-event-callback-%%

  • since: v1.9

async method: Page.waitForConsoleMessage

  • since: v1.9
  • langs: java, python, csharp
    • alias-python: expect_console_message
    • alias-csharp: RunAndWaitForConsoleMessage
  • returns: <[ConsoleMessage]>

Performs action and waits for a [ConsoleMessage] to be logged by in the page. If predicate is provided, it passes [ConsoleMessage] value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the [event: Page.console] event is fired.

async method: Page.waitForConsoleMessage

  • since: v1.9
  • langs: python
  • returns: <[EventContextManager]<[ConsoleMessage]>>

param: Page.waitForConsoleMessage.action = %%-csharp-wait-for-event-action-%%

  • since: v1.12

option: Page.waitForConsoleMessage.predicate

  • since: v1.9
  • predicate <[function]([ConsoleMessage]):[boolean]>

Receives the [ConsoleMessage] object and resolves to truthy value when the waiting should resolve.

option: Page.waitForConsoleMessage.timeout = %%-wait-for-event-timeout-%%

  • since: v1.9

param: Page.waitForConsoleMessage.callback = %%-java-wait-for-event-callback-%%

  • since: v1.9

async method: Page.waitForDownload

  • since: v1.9
  • langs: java, python, csharp
    • alias-python: expect_download
    • alias-csharp: RunAndWaitForDownload
  • returns: <[Download]>

Performs action and waits for a new [Download]. If predicate is provided, it passes [Download] value into the predicate function and waits for predicate(download) to return a truthy value. Will throw an error if the page is closed before the download event is fired.

async method: Page.waitForDownload

  • since: v1.9
  • langs: python
  • returns: <[EventContextManager]<[Download]>>

param: Page.waitForDownload.action = %%-csharp-wait-for-event-action-%%

  • since: v1.12

option: Page.waitForDownload.predicate

  • since: v1.9
  • predicate <[function]([Download]):[boolean]>

Receives the [Download] object and resolves to truthy value when the waiting should resolve.

option: Page.waitForDownload.timeout = %%-wait-for-event-timeout-%%

  • since: v1.9

param: Page.waitForDownload.callback = %%-java-wait-for-event-callback-%%

  • since: v1.9

async method: Page.waitForEvent

  • since: v1.8
  • langs: js, python
    • alias-python: expect_event
  • returns: <[any]>

Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the page is closed before the event is fired. Returns the event data value.

Usage

1// Start waiting for download before clicking. Note no await. 2const downloadPromise = page.waitForEvent('download'); 3await page.getByText('Download file').click(); 4const download = await downloadPromise; 5
1async with page.expect_event("framenavigated") as event_info: 2 await page.get_by_role("button") 3frame = await event_info.value 4
1with page.expect_event("framenavigated") as event_info: 2 page.get_by_role("button") 3frame = event_info.value 4

async method: Page.waitForEvent

  • since: v1.8
  • langs: python
  • returns: <[EventContextManager]>

param: Page.waitForEvent.event = %%-wait-for-event-event-%%

  • since: v1.8

param: Page.waitForEvent.optionsOrPredicate

  • since: v1.8
  • langs: js
  • optionsOrPredicate ?<[function]|[Object]>
    • predicate <[function]> Receives the event data and resolves to truthy value when the waiting should resolve.
    • timeout ?<[float]> Maximum time to wait for in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the [method: BrowserContext.setDefaultTimeout] or [method: Page.setDefaultTimeout] methods.

Either a predicate that receives an event or an options object. Optional.

option: Page.waitForEvent.predicate = %%-wait-for-event-predicate-%%

  • since: v1.8

option: Page.waitForEvent.timeout = %%-wait-for-event-timeout-%%

  • since: v1.8

async method: Page.waitForFileChooser

  • since: v1.9
  • langs: java, python, csharp
    • alias-python: expect_file_chooser
    • alias-csharp: RunAndWaitForFileChooser
  • returns: <[FileChooser]>

Performs action and waits for a new [FileChooser] to be created. If predicate is provided, it passes [FileChooser] value into the predicate function and waits for predicate(fileChooser) to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.

async method: Page.waitForFileChooser

  • since: v1.9
  • langs: python
  • returns: <[EventContextManager]<[FileChooser]>>

param: Page.waitForFileChooser.action = %%-csharp-wait-for-event-action-%%

  • since: v1.12

option: Page.waitForFileChooser.predicate

  • since: v1.9
  • predicate <[function]([FileChooser]):[boolean]>

Receives the [FileChooser] object and resolves to truthy value when the waiting should resolve.

option: Page.waitForFileChooser.timeout = %%-wait-for-event-timeout-%%

  • since: v1.9

param: Page.waitForFileChooser.callback = %%-java-wait-for-event-callback-%%

  • since: v1.9

async method: Page.waitForFunction

  • since: v1.8
  • returns: <[JSHandle]>

Returns when the [param: expression] returns a truthy value. It resolves to a JSHandle of the truthy value.

Usage

The [method: Page.waitForFunction] can be used to observe viewport size change:

1const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. 2 3(async () => { 4 const browser = await webkit.launch(); 5 const page = await browser.newPage(); 6 const watchDog = page.waitForFunction(() => window.