Page.waitForRequest() waits for network request
Page.waitForRequest() waits for a network request matching a URL pattern. It returns a Promise that resolves to the Request object. The method takes a URL pattern as parameter, which can use wildcards like '**/*logo*.png'. The waiting must be started before the action that triggers the request, without awaiting the returned promise initially.
Page.waitForEvent('popup') waits for popup window
Page.waitForEvent('popup') waits for a new popup window to be created. It returns a Promise that resolves to the new Page object representing the popup. The waiting must be started before the action that creates the popup, without awaiting the returned promise initially.
Page.on() adds event listener
Page.on() adds an event listener that handles events. It takes the event name as a string (such as 'request' or 'requestfinished') and a callback function. The callback function receives the event object as a parameter. The listener remains active until explicitly removed.
Page.off() removes event listener
Page.off() removes a previously added event listener. It takes the event name as a string and the callback function reference to remove. Only the specified listener is removed; other listeners for the same event remain active.
Page.once() adds one-off event listener
Page.once() adds an event listener that fires only once. It takes the event name as a string and a callback function. After the event occurs, the listener is automatically removed.
Request event fired when network request is sent
The 'request' event is fired when a network request is sent from the page. The event listener receives a Request object as a parameter.
Requestfinished event fired when network request finishes
The 'requestfinished' event is fired when a network request completes. The event listener receives a Request object as a parameter.
Dialog event fires when page shows dialog
The 'dialog' event is fired when a dialog (such as alert, prompt, or confirm) appears on the page. The event listener receives a Dialog object as a parameter.
Event waiting pattern for typical use cases
When waiting for an event, the common pattern is to start waiting (without awaiting) before performing the action that triggers the event. This ensures the listener is in place before the event occurs. For example: const promise = page.waitForEvent('eventname'); await actionThatTriggersEvent(); const result = await promise;
Multiple event listeners can be added for same event
Multiple listeners can be added to the same event using page.on() or page.once(). Each listener is independent and handles the event separately.
Page.emulateMedia() method signature and colorScheme parameter
The emulateMedia() method accepts an object with media emulation options. The colorScheme property can be set to 'dark' or 'light'. The reducedMotion property can be set to 'reduce'. The media property can be set to 'print'.
Page.waitForLoadState() with networkidle parameter
The waitForLoadState() method accepts a load state string as parameter. One supported load state is 'networkidle'.
Page.waitForFunction() accepts callback function
The waitForFunction() method accepts a callback function that returns a boolean or truthy value. The method waits for the function to return true before proceeding.
Page.waitForEvent('download') for file downloads
The waitForEvent() method accepts 'download' as an event type. It returns a promise that resolves when a download is triggered. The resolved Download object has methods including saveAs() and a suggestedFilename() property.
Page.waitForURL() waits for URL matching pattern
The waitForURL() method is an async method that waits for the page URL to match the provided URL pattern (e.g., '**/dashboard').
Frame.waitForFunction returns JSHandle when expression becomes truthy
Frame.waitForFunction returns a JSHandle. It waits for the expression to return a truthy value, then returns that value.
Frame.waitForFunction parameters and options
Frame.waitForFunction accepts the following parameters and options:
- expression (required): JavaScript expression or PageFunction to evaluate, since v1.8
- arg (optional, EvaluationArgument): optional argument to pass to the expression, since v1.8
- polling (optional): polling strategy, since v1.8
- timeout (optional): timeout in milliseconds, since v1.8
- signal (optional): since v1.8
Frame.waitForFunction example - observing viewport size change
This example demonstrates using Frame.waitForFunction to observe viewport size changes:
```js
const { firefox } = require('playwright');
(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
await page.setViewportSize({ width: 50, height: 50 });
await watchDog;
await browser.close();
})();
```
Frame.waitForFunction example - Python async with argument
This example demonstrates using Frame.waitForFunction with an argument in Python async:
```python async
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch()
page = await browser.new_page()
await page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);")
await page.main_frame.wait_for_function("() => window.x > 0")
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
```
Frame.waitForFunction example - passing argument to predicate
This example shows how to pass an argument to the predicate of frame.waitForFunction:
```js
const selector = '.foo';
await frame.waitForFunction(selector => !!document.querySelector(selector), selector);
```
```python async
selector = ".foo"
await frame.wait_for_function("selector => !!document.querySelector(selector)", selector)
```
Frame.waitForLoadState waits for required load state to be reached
Frame.waitForLoadState waits for the required load state to be reached. It returns when the frame reaches a required load state, with 'load' as the default. The navigation must have been committed when this method is called. If the current document has already reached the required state, it resolves immediately. Most of the time this method is not needed because Playwright auto-waits before every action.
Frame.waitForLoadState parameters and options
Frame.waitForLoadState accepts the following parameters and options:
- state (optional): load state to wait for ('domcontentloaded', 'load', 'networkidle'), since v1.8
- timeout (optional): timeout in milliseconds, since v1.8
- signal (optional): AbortSignal to cancel waiting, since v1.8
Frame.waitForLoadState example - waiting for load state after click
This example shows basic usage of Frame.waitForLoadState:
```js
await frame.click('button'); // Click triggers navigation.
await frame.waitForLoadState(); // Waits for 'load' state by default.
```
```python async
await frame.click("button") # click triggers navigation.
await frame.wait_for_load_state() # the promise resolves after "load" event.
```
Frame.waitForTimeout waits for given timeout in milliseconds
Frame.waitForTimeout waits for the given timeout in milliseconds. This method is discouraged and should only be used for debugging. Tests using the timer in production are flaky. Use signals such as network events and selectors becoming visible instead.
Frame.waitForTimeout parameter
Frame.waitForTimeout accepts the following parameter:
- timeout (required, float): a timeout to wait for in milliseconds, since v1.8
Locator.waitFor() waits until element satisfies state condition
Locator.waitFor() returns when the element specified by the locator satisfies the state option. If the target element already satisfies the condition, it returns immediately. Otherwise, waits up to the timeout milliseconds until the condition is met. Options: state (condition to wait for), timeout, signal. Available since v1.16.
Locator.waitForFunction() waits for custom condition with expression
Locator.waitForFunction() returns when the provided expression returns a truthy value, with the matching element as the first argument and optional arg parameter as the second. The locator is re-resolved on each retry, tolerating element re-rendering. If the expression returns a Promise, the method waits for the promise to resolve before checking its value. Parameters: expression (function/code string), arg (optional EvaluationArgument to pass to expression). Options: timeout, signal. Available since v1.62.
Locator.waitFor() example waiting for element visibility
Example showing Locator.waitFor() usage:
```python
order_sent = page.locator("#order-sent")
await order_sent.wait_for()
```
This waits for the element with id 'order-sent' to appear or reach the specified state.
Locator.waitForFunction() example waiting for attribute
Example showing Locator.waitForFunction() usage to wait for an attribute:
```js
const toggle = page.getByRole('button', { name: 'Menu' });
await toggle.click();
await toggle.waitForFunction(element => element.hasAttribute('aria-expanded'));
```
And passing an argument:
```js
await page.getByTestId('status').waitForFunction((element, value) => {
return element.textContent === value;
}, 'Ready');
```
wait-for-selector-state: WaitForSelectorState options
The state parameter accepts 'attached', 'detached', 'visible', or 'hidden'. Defaults to 'visible'. 'attached': wait for element in DOM. 'detached': wait for element not in DOM. 'visible': wait for non-empty bounding box and no visibility:hidden. 'hidden': wait for detached or empty bounding box or visibility:hidden.
js-python-wait-for-function-polling: polling parameter
The polling parameter is type float or 'raf'. If 'raf', expression executed in requestAnimationFrame callback. If number, treated as interval in milliseconds for function execution. Defaults to 'raf'.
csharp-java-wait-for-function-polling: pollingInterval parameter
The pollingInterval parameter is type float. If specified, treated as interval in milliseconds for function execution. By default (if not specified), expression executed in requestAnimationFrame callback.
remove-all-listeners-options-behavior for JavaScript
The behavior parameter is RemoveAllListenersBehavior ('wait', 'ignoreErrors', 'default'). 'default': do not wait for listener calls, error may result in unhandled error. 'wait': wait for calls to finish. 'ignoreErrors': no wait, errors silently caught. Since v1.47.
wait-for-event-event parameter
The event parameter is type string. Event name, same as passed to *.on(event).
wait-for-load-state-state parameter
The state parameter is optional LoadState ('load', 'domcontentloaded', 'networkidle'). Optional load state to wait for, defaults to 'load'. If already reached, resolves immediately. 'load': wait for load event. 'domcontentloaded': wait for DOMContentLoaded. 'networkidle': DISCOURAGED, wait for no network for 500ms.
java-wait-for-event-callback
The callback parameter is type Runnable. Callback that performs action triggering event.
csharp-wait-for-event-action
The action parameter is type Func<Task>. Action that triggers event.
wait-for-event-predicate parameter
The predicate parameter is type function receiving event data, resolves to truthy value when waiting should resolve.
wait-for-event-timeout for C#, Java, Python
The timeout parameter is type float. Maximum time to wait in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable. Default changeable via BrowserContext.setDefaultTimeout.
js-assertions-timeout for JavaScript
The timeout parameter is type float. Time to retry assertion in milliseconds. Defaults to timeout in TestConfig.expect.
js-assertions-signal for JavaScript
The signal parameter is type AbortSignal. Optional signal canceling assertion. Aborting fails assertion like timeout: if aborted while retrying or before start, assertion fails without further retry. Since v1.62.
csharp-java-python-assertions-timeout
The timeout parameter is type float. Time to retry assertion in milliseconds. Defaults to 5000.
Page.waitForClose method
Page.waitForClose() (async, added in v1.11, Java only) performs action and waits for the Page to close. Returns the Page. Options: timeout, signal. Parameter: callback (action to perform).
Page emits events using EventEmitter methods
The Page class emits various events which can be handled using Node's native EventEmitter methods such as on, once, or removeListener. Example: page.once('load', () => console.log('Page loaded!')). To unsubscribe use the removeListener method.
Page.clock property for mocking time
Page has a clock property of type Clock (since v1.45). Playwright has the ability to mock clock and passage of time through this property.
Page.close event emitted when page closes
The close event is emitted when the page closes. The event handler receives the Page instance as an argument.
Page.console event logs console API calls
The console event is emitted when JavaScript within the page calls console API methods like console.log or console.dir. The event handler receives a ConsoleMessage instance. The arguments passed into console.log are available on the ConsoleMessage via msg.args().
Page.crash event emitted on page crash
The crash event is 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 exception message contains 'crash'.
Page.dialog event requires accept or dismiss
The dialog event is emitted when a JavaScript dialog appears (alert, prompt, confirm, or beforeunload). The listener must either call Dialog.accept() or Dialog.dismiss() on the dialog - otherwise the page will freeze waiting for the dialog. When no Page.dialog or BrowserContext.dialog listeners are present, all dialogs are automatically dismissed.
Page.dialogClosed event emitted when dialog closes
The dialogClosed event is emitted when a JavaScript dialog has been closed, either by Dialog.accept(), Dialog.dismiss(), or manually by the user in the headed browser (since v1.63).
Page.DOMContentLoaded event on document ready
The DOMContentLoaded event is emitted when the JavaScript DOMContentLoaded event is dispatched (since v1.9).
Page.download event emitted on attachment download
The download event is emitted when attachment download started (since v1.8). User can access basic file operations on downloaded content via the passed Download instance.
Page.fileChooser event for file input handling
The fileChooser event is emitted when a file chooser is supposed to appear, such as after clicking <input type=file> (since v1.9). Playwright can respond via FileChooser.setFiles() that can be uploaded after that.
Page.frameAttached event on frame attachment
The frameAttached event is emitted when a frame is attached (since v1.9). The event handler receives a Frame instance.
Page.frameDetached event on frame detachment
The frameDetached event is emitted when a frame is detached (since v1.9). The event handler receives a Frame instance.
Page.frameNavigated event on frame navigation
The frameNavigated event is emitted when a frame is navigated to a new URL (since v1.9). The event handler receives a Frame instance.
Page.load event emitted on window load
The load event is emitted when the JavaScript load event is dispatched (since v1.8).
Page.pageError event for uncaught exceptions
The pageError event is emitted when an uncaught exception happens within the page (since v1.9). The event handler receives an Error instance.
Page.popup event for new tabs and windows
The popup event is emitted when the page opens a new tab or window (since v1.8). This event is emitted in addition to 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. The event handler receives a Page instance.
Page.worker event for dedicated web workers
The worker event is emitted when a dedicated WebWorker is spawned by the page (since v1.8). The event handler receives a Worker instance.