NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.
Returns the ElementHandle pointing to the frame element.
NOTE The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead.
The method finds an element matching the specified selector within the frame. If no elements match the selector,
returns null
.
A selector to query for.
Optional
options: { Optional
NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.
Returns the ElementHandle pointing to the frame element.
NOTE The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead.
The method finds an element matching the specified selector within the frame. If no elements match the selector,
returns null
.
A selector to query for.
Optional
options: { Optional
NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.
Returns the ElementHandles pointing to the frame elements.
NOTE The use of ElementHandle is discouraged, use Locator objects instead.
The method finds all elements matching the specified selector within the frame. If no elements match the selector, returns empty array.
A selector to query for.
NOTE Use locator-based frame.locator(selector[, options]) instead. Read more about locators.
Returns the ElementHandles pointing to the frame elements.
NOTE The use of ElementHandle is discouraged, use Locator objects instead.
The method finds all elements matching the specified selector within the frame. If no elements match the selector, returns empty array.
A selector to query for.
NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.
Returns the return value of pageFunction
.
The method finds all elements matching the specified selector within the frame and passes an array of matched
elements as a first argument to pageFunction
.
If pageFunction
returns a [Promise], then
frame.$$eval(selector, pageFunction[, arg])
would wait for the promise to resolve and return its value.
Usage
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
A selector to query for.
Function to be evaluated in the page context.
Optional argument to pass to pageFunction
.
NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.
Returns the return value of pageFunction
.
The method finds all elements matching the specified selector within the frame and passes an array of matched
elements as a first argument to pageFunction
.
If pageFunction
returns a [Promise], then
frame.$$eval(selector, pageFunction[, arg])
would wait for the promise to resolve and return its value.
Usage
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
A selector to query for.
Function to be evaluated in the page context.
Optional argument to pass to pageFunction
.
NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.
Returns the return value of pageFunction
.
The method finds all elements matching the specified selector within the frame and passes an array of matched
elements as a first argument to pageFunction
.
If pageFunction
returns a [Promise], then
frame.$$eval(selector, pageFunction[, arg])
would wait for the promise to resolve and return its value.
Usage
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
A selector to query for.
Function to be evaluated in the page context.
Optional
arg: anyOptional argument to pass to pageFunction
.
Optional
NOTE In most cases, locator.evaluateAll(pageFunction[, arg]), other Locator helper methods and web-first assertions do a better job.
Returns the return value of pageFunction
.
The method finds all elements matching the specified selector within the frame and passes an array of matched
elements as a first argument to pageFunction
.
If pageFunction
returns a [Promise], then
frame.$$eval(selector, pageFunction[, arg])
would wait for the promise to resolve and return its value.
Usage
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
A selector to query for.
Function to be evaluated in the page context.
Optional
arg: anyOptional argument to pass to pageFunction
.
Optional
NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.
Returns the return value of pageFunction
.
The method finds an element matching the specified selector within the frame and passes it as a first argument to
pageFunction
. If no elements match the selector, the method throws an error.
If pageFunction
returns a [Promise], then
frame.$eval(selector, pageFunction[, arg, options])
would wait for the promise to resolve and return its value.
Usage
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
A selector to query for.
Function to be evaluated in the page context.
Optional argument to pass to pageFunction
.
NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.
Returns the return value of pageFunction
.
The method finds an element matching the specified selector within the frame and passes it as a first argument to
pageFunction
. If no elements match the selector, the method throws an error.
If pageFunction
returns a [Promise], then
frame.$eval(selector, pageFunction[, arg, options])
would wait for the promise to resolve and return its value.
Usage
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
A selector to query for.
Function to be evaluated in the page context.
Optional argument to pass to pageFunction
.
NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.
Returns the return value of pageFunction
.
The method finds an element matching the specified selector within the frame and passes it as a first argument to
pageFunction
. If no elements match the selector, the method throws an error.
If pageFunction
returns a [Promise], then
frame.$eval(selector, pageFunction[, arg, options])
would wait for the promise to resolve and return its value.
Usage
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
A selector to query for.
Function to be evaluated in the page context.
Optional
arg: anyOptional argument to pass to pageFunction
.
Optional
NOTE This method does not wait for the element to pass the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(pageFunction[, arg, options]), other Locator helper methods or web-first assertions instead.
Returns the return value of pageFunction
.
The method finds an element matching the specified selector within the frame and passes it as a first argument to
pageFunction
. If no elements match the selector, the method throws an error.
If pageFunction
returns a [Promise], then
frame.$eval(selector, pageFunction[, arg, options])
would wait for the promise to resolve and return its value.
Usage
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
A selector to query for.
Function to be evaluated in the page context.
Optional
arg: anyOptional argument to pass to pageFunction
.
Optional
Returns the added tag when the script's onload fires or when the script content was injected into frame.
Adds a <script>
tag into the page with the desired url or content.
Optional
options: { Optional
Optional
content?: stringRaw JavaScript content to be injected into frame.
Optional
path?: stringPath 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.
Optional
type?: stringScript type. Use 'module' in order to load a Javascript ES6 module. See script for more details.
Optional
url?: stringURL of a script to be added.
Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
Adds a <link rel="stylesheet">
tag into the page with the desired url or a <style type="text/css">
tag with the
content.
Optional
options: { Optional
Optional
content?: stringRaw CSS content to be injected into frame.
Optional
path?: stringPath 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.
Optional
url?: stringURL of the <link>
tag.
NOTE Use locator-based locator.check([options]) instead. Read more about locators.
This method checks an element matching selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If
the element is detached during the checks, the whole action is retried.noWaitAfter
option is set.When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError. Passing zero timeout disables this.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
position?: { A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
NOTE Use locator-based locator.click([options]) instead. Read more about locators.
This method clicks an element matching selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If
the element is detached during the checks, the whole action is retried.position
.noWaitAfter
option is set.When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError. Passing zero timeout disables this.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
button?: "left" | "right" | "middle"Defaults to left
.
Optional
clickdefaults to 1. See [UIEvent.detail].
Optional
delay?: numberTime to wait between mousedown
and mouseup
in milliseconds. Defaults to 0.
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
position?: { A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
NOTE Use locator-based locator.dblclick([options]) instead. Read more about locators.
This method double clicks an element matching selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If
the element is detached during the checks, the whole action is retried.position
.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 timeout
, this method throws a TimeoutError. Passing zero timeout disables this.
NOTE frame.dblclick()
dispatches two click
events and a single dblclick
event.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
button?: "left" | "right" | "middle"Defaults to left
.
Optional
delay?: numberTime to wait between mousedown
and mouseup
in milliseconds. Defaults to 0.
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
position?: { A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
NOTE Use locator-based locator.dispatchEvent(type[, eventInit, options]) 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
await frame.dispatchEvent('button#submit', 'click');
Under the hood, it creates an instance of an event based on the given type
, initializes it with eventInit
properties and dispatches it on the element. Events are composed
, cancelable
and bubble by default.
Since 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:
// Note you can only create DataTransfer in Chromium and Firefox
const dataTransfer = await frame.evaluateHandle(() => new DataTransfer());
await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
DOM event type: "click"
, "dragstart"
, etc.
Optional
eventInit: EvaluationArgumentOptional event-specific initialization properties.
Optional
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
sourceClicks on the source element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
targetDrops on the target element at this point relative to the top-left corner of the element's padding box. If not specified, some visible point of the element is used.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
Returns the return value of pageFunction
.
If the function passed to the frame.evaluate(pageFunction[, arg]) returns a [Promise], then frame.evaluate(pageFunction[, arg]) would wait for the promise to resolve and return its value.
If the function passed to the
frame.evaluate(pageFunction[, arg]) returns a
non-[Serializable] value, then
frame.evaluate(pageFunction[, arg]) returns
undefined
. Playwright also supports transferring some additional values that are not serializable by JSON
:
-0
, NaN
, Infinity
, -Infinity
.
Usage
const result = await frame.evaluate(([x, y]) => {
return Promise.resolve(x * y);
}, [7, 8]);
console.log(result); // prints "56"
A string can also be passed in instead of a function.
console.log(await frame.evaluate('1 + 2')); // prints "3"
ElementHandle instances can be passed as an argument to the frame.evaluate(pageFunction[, arg]):
const bodyHandle = await frame.evaluate('document.body');
const html = await frame.evaluate(([body, suffix]) =>
body.innerHTML + suffix, [bodyHandle, 'hello'],
);
await bodyHandle.dispose();
Function to be evaluated in the page context.
Optional argument to pass to pageFunction
.
Returns the return value of pageFunction
.
If the function passed to the frame.evaluate(pageFunction[, arg]) returns a [Promise], then frame.evaluate(pageFunction[, arg]) would wait for the promise to resolve and return its value.
If the function passed to the
frame.evaluate(pageFunction[, arg]) returns a
non-[Serializable] value, then
frame.evaluate(pageFunction[, arg]) returns
undefined
. Playwright also supports transferring some additional values that are not serializable by JSON
:
-0
, NaN
, Infinity
, -Infinity
.
Usage
const result = await frame.evaluate(([x, y]) => {
return Promise.resolve(x * y);
}, [7, 8]);
console.log(result); // prints "56"
A string can also be passed in instead of a function.
console.log(await frame.evaluate('1 + 2')); // prints "3"
ElementHandle instances can be passed as an argument to the frame.evaluate(pageFunction[, arg]):
const bodyHandle = await frame.evaluate('document.body');
const html = await frame.evaluate(([body, suffix]) =>
body.innerHTML + suffix, [bodyHandle, 'hello'],
);
await bodyHandle.dispose();
Function to be evaluated in the page context.
Optional
arg: anyOptional argument to pass to pageFunction
.
Optional
Returns the return value of pageFunction
as a JSHandle.
The only difference between frame.evaluate(pageFunction[, arg]) and frame.evaluateHandle(pageFunction[, arg]) is that frame.evaluateHandle(pageFunction[, arg]) returns JSHandle.
If the function, passed to the frame.evaluateHandle(pageFunction[, arg]), returns a [Promise], then frame.evaluateHandle(pageFunction[, arg]) would wait for the promise to resolve and return its value.
Usage
// Handle for the window object
const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
A string can also be passed in instead of a function.
const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.
JSHandle instances can be passed as an argument to the frame.evaluateHandle(pageFunction[, arg]):
const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(([body, suffix]) =>
body.innerHTML + suffix, [aHandle, 'hello'],
);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
Function to be evaluated in the page context.
Optional argument to pass to pageFunction
.
Returns the return value of pageFunction
as a JSHandle.
The only difference between frame.evaluate(pageFunction[, arg]) and frame.evaluateHandle(pageFunction[, arg]) is that frame.evaluateHandle(pageFunction[, arg]) returns JSHandle.
If the function, passed to the frame.evaluateHandle(pageFunction[, arg]), returns a [Promise], then frame.evaluateHandle(pageFunction[, arg]) would wait for the promise to resolve and return its value.
Usage
// Handle for the window object
const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
A string can also be passed in instead of a function.
const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.
JSHandle instances can be passed as an argument to the frame.evaluateHandle(pageFunction[, arg]):
const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(([body, suffix]) =>
body.innerHTML + suffix, [aHandle, 'hello'],
);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
Function to be evaluated in the page context.
Optional
arg: anyOptional argument to pass to pageFunction
.
Optional
NOTE Use locator-based locator.fill(value[, options]) instead. Read more about locators.
This method waits for an element matching 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 locator.pressSequentially(text[, options]).
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Value to fill for the <input>
, <textarea>
or [contenteditable]
element.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.focus([options]) instead. Read more about locators.
This method fetches an element with selector
and focuses it. If there's no element matching selector
, the
method waits until a matching element appears in the DOM.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Returns the frame
or iframe
element handle which corresponds to this frame.
This is an inverse of elementHandle.contentFrame(). Note that returned handle actually belongs to the parent frame.
This method throws an error if the frame has been detached before frameElement()
returns.
Usage
const frameElement = await frame.frameElement();
const contentFrame = await frameElement.contentFrame();
console.log(frame === contentFrame); // -> true
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">
:
const locator = frame.frameLocator('#my-iframe').getByText('Submit');
await locator.click();
A selector to use when resolving DOM element.
NOTE Use locator-based locator.getAttribute(name[, options]) instead. Read more about locators.
Returns element attribute value.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Attribute name to get the value for.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Allows locating elements by their alt text.
Usage
For example, this method will find the image by alt text "Playwright logo":
<img alt='Playwright logo'>
await page.getByAltText('Playwright logo').click();
Text to locate the element for.
Optional
options: { Optional
Optional
exact?: booleanWhether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.
Allows locating input elements by the text of the associated <label>
or aria-labelledby
element, or by the
aria-label
attribute.
Usage
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
<input aria-label="Username">
<label for="password-input">Password:</label>
<input id="password-input">
await page.getByLabel('Username').fill('john');
await page.getByLabel('Password').fill('secret');
Text to locate the element for.
Optional
options: { Optional
Optional
exact?: booleanWhether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.
Allows locating input elements by the placeholder text.
Usage
For example, consider the following DOM structure.
<input type="email" placeholder="name@example.com" />
You can fill the input after locating it by the placeholder text:
await page
.getByPlaceholder('name@example.com')
.fill('playwright@microsoft.com');
Text to locate the element for.
Optional
options: { Optional
Optional
exact?: booleanWhether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.
Allows locating elements by their ARIA role, ARIA attributes and accessible name.
Usage
Consider the following DOM structure.
<h3>Sign up</h3>
<label>
<input type="checkbox" /> Subscribe
</label>
<br/>
<button>Submit</button>
You can locate each element by it's implicit role:
await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
await page.getByRole('checkbox', { name: 'Subscribe' }).check();
await page.getByRole('button', { name: /submit/i }).click();
Details
Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
Many html elements have an implicitly defined role
that is recognized by the role selector. You can find all the
supported roles here. ARIA guidelines do not recommend
duplicating implicit roles and attributes by setting role
and/or aria-*
attributes to default values.
Required aria role.
Optional
options: { Optional
Optional
checked?: booleanAn attribute that is usually set by aria-checked
or native <input type=checkbox>
controls.
Learn more about aria-checked
.
Optional
disabled?: booleanAn attribute that is usually set by aria-disabled
or disabled
.
NOTE Unlike most other attributes, disabled
is inherited through the DOM hierarchy. Learn more about
aria-disabled
.
Optional
exact?: booleanWhether name
is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when name
is a
regular expression. Note that exact match still trims whitespace.
Optional
expanded?: booleanAn attribute that is usually set by aria-expanded
.
Learn more about aria-expanded
.
Optional
includeOption that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector.
Learn more about aria-hidden
.
Optional
level?: numberA number attribute that is usually present for roles heading
, listitem
, row
, treeitem
, with default values
for <h1>-<h6>
elements.
Learn more about aria-level
.
Optional
name?: string | RegExpOption to match the accessible name. By default, matching is
case-insensitive and searches for a substring, use exact
to control this behavior.
Learn more about accessible name.
Optional
pressed?: booleanAn attribute that is usually set by aria-pressed
.
Learn more about aria-pressed
.
Optional
selected?: booleanAn attribute that is usually set by aria-selected
.
Learn more about aria-selected
.
Locate element by the test id.
Usage
Consider the following DOM structure.
<button data-testid="directions">Itinéraire</button>
You can locate the element by it's test id:
await page.getByTestId('directions').click();
Details
By default, the data-testid
attribute is used as a test id. Use
selectors.setTestIdAttribute(attributeName)
to configure a different test id attribute if necessary.
// Set custom test id attribute from @playwright/test config:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
testIdAttribute: 'data-pw'
},
});
Id to locate the element by.
Allows locating elements that contain given text.
See also locator.filter([options]) that allows to match by another criteria, like an accessible role, and then filter by the text content.
Usage
Consider the following DOM structure:
<div>Hello <span>world</span></div>
<div>Hello</div>
You can locate by text substring, exact string, or a regular expression:
// Matches <span>
page.getByText('world');
// Matches first <div>
page.getByText('Hello world');
// Matches second <div>
page.getByText('Hello', { exact: true });
// Matches both <div>s
page.getByText(/Hello/);
// Matches second <div>
page.getByText(/^hello$/i);
Details
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type button
and submit
are matched by their value
instead of the text content. For
example, locating by text "Log in"
matches <input type=button value="Log in">
.
Text to locate the element for.
Optional
options: { Optional
Optional
exact?: booleanWhether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.
Allows locating elements by their title attribute.
Usage
Consider the following DOM structure.
<span title='Issues count'>25 issues</span>
You can check the issues count after locating it by the title text:
await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
Text to locate the element for.
Optional
options: { Optional
Optional
exact?: booleanWhether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace.
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
The method will throw an error if:
timeout
is exceeded during navigation.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 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.
URL to navigate frame to. The url should include scheme, e.g. https://
.
Optional
options: { Optional
Optional
referer?: stringReferer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders(headers).
Optional
timeout?: numberMaximum operation time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via
navigationTimeout
option in the config, or by using the
browserContext.setDefaultNavigationTimeout(timeout),
browserContext.setDefaultTimeout(timeout),
page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
waitWhen to consider operation succeeded, defaults to load
. Events can be either:
'domcontentloaded'
- consider operation to be finished when the DOMContentLoaded
event is fired.'load'
- consider operation to be finished when the load
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for
at least 500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started
loading.NOTE Use locator-based locator.hover([options]) instead. Read more about locators.
This method hovers over an element matching selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If
the element is detached during the checks, the whole action is retried.position
.noWaitAfter
option is set.When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError. Passing zero timeout disables this.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
position?: { A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
NOTE Use locator-based locator.innerHTML([options]) instead. Read more about locators.
Returns element.innerHTML
.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.innerText([options]) instead. Read more about locators.
Returns element.innerText
.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.inputValue([options]) instead. Read more about locators.
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.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.isChecked([options]) instead. Read more about locators.
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.isDisabled([options]) instead. Read more about locators.
Returns whether the element is disabled, the opposite of enabled.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.isEditable([options]) instead. Read more about locators.
Returns whether the element is editable.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Returns whether the element is enabled.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.isHidden([options]) instead. Read more about locators.
Returns whether the element is hidden, the opposite of visible. selector
that
does not match any elements is considered hidden.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberThis option is ignored. frame.isHidden(selector[, options]) does not wait for the element to become hidden and returns immediately.
NOTE Use locator-based locator.isVisible([options]) instead. Read more about locators.
Returns whether the element is visible. selector
that does not match any elements
is considered not visible.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberThis option is ignored. frame.isVisible(selector[, options]) does not wait for the element to become visible and returns immediately.
The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
A selector to use when resolving DOM element.
Optional
options: { Optional
Optional
has?: LocatorNarrows down the results of the method to those which contain elements matching this relative locator. For example,
article
that has text=Playwright
matches <article><div>Playwright</div></article>
.
Inner locator must be relative to the outer locator and is queried starting with the outer locator match, not
the document root. For example, you can find content
that has div
in
<article><content><div>Playwright</div></content></article>
. However, looking for content
that has article div
will fail, because the inner locator must be relative and should not use any elements outside the content
.
Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.
Optional
hasMatches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
outer one. For example, article
that does not have div
matches <article><span>Playwright</span></article>
.
Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.
Optional
hasMatches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element. When passed a [string], matching is case-insensitive and searches for a substring.
Optional
hasMatches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
passed a [string], matching is case-insensitive and searches for a substring. For example, "Playwright"
matches
<article><div>Playwright</div></article>
.
NOTE Use locator-based locator.press(key[, options]) instead. Read more about locators.
key
can specify the intended
keyboardEvent.key value or a single character
to generate the text for. A superset of the 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
,
ControlOrMeta
. ControlOrMeta
resolves to Control
on Windows and Linux and to Meta
on macOS.
Holding down Shift
will type the text that corresponds to the key
in the upper case.
If 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"
, key: "Control++
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.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Name of the key to press or a character to generate, such as ArrowLeft
or a
.
Optional
options: { Optional
Optional
delay?: numberTime to wait between keydown
and keyup
in milliseconds. Defaults to 0.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.selectOption(values[, options]) instead. Read more about locators.
This method waits for an element matching 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
// Single selection matching the value or label
frame.selectOption('select#colors', 'blue');
// single selection matching both the value and the label
frame.selectOption('select#colors', { label: 'Blue' });
// multiple selection
frame.selectOption('select#colors', 'red', 'green', 'blue');
A selector to query for.
Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise
only the first option matching one of the passed options is selected. String values are matching both values and
labels. Option is considered matching if all specified properties match.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.setChecked(checked[, options]) instead. Read more about locators.
This method checks or unchecks an element matching selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If
the element is detached during the checks, the whole action is retried.noWaitAfter
option is set.When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError. Passing zero timeout disables this.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Whether to check or uncheck the checkbox.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
position?: { A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
HTML markup to assign to the page.
Optional
options: { Optional
Optional
timeout?: numberMaximum operation time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via
navigationTimeout
option in the config, or by using the
browserContext.setDefaultNavigationTimeout(timeout),
browserContext.setDefaultTimeout(timeout),
page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
waitWhen to consider operation succeeded, defaults to load
. Events can be either:
'domcontentloaded'
- consider operation to be finished when the DOMContentLoaded
event is fired.'load'
- consider operation to be finished when the load
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for
at least 500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started
loading.NOTE Use locator-based locator.setInputFiles(files[, options]) 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 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.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
NOTE Use locator-based locator.tap([options]) instead. Read more about locators.
This method taps an element matching selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If
the element is detached during the checks, the whole action is retried.position
.noWaitAfter
option is set.When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError. Passing zero timeout disables this.
NOTE frame.tap()
requires that the hasTouch
option of the browser context be set to true.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
modifiers?: ("Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift")[]Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
position?: { A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
NOTE Use locator-based locator.textContent([options]) instead. Read more about locators.
Returns element.textContent
.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Sends a keydown
, keypress
/input
, and keyup
event for each character in the text. frame.type
can be used
to send fine-grained keyboard events. To fill values in form fields, use
frame.fill(selector, value[, options]).
To press a special key, like Control
or ArrowDown
, use
keyboard.press(key[, options]).
Usage
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
A text to type into a focused element.
Optional
options: { Optional
Optional
delay?: numberTime to wait between key presses in milliseconds. Defaults to 0.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
In most cases, you should use locator.fill(value[, options]) instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use locator.pressSequentially(text[, options]).
NOTE Use locator-based locator.uncheck([options]) instead. Read more about locators.
This method checks an element matching selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If
the element is detached during the checks, the whole action is retried.noWaitAfter
option is set.When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError. Passing zero timeout disables this.
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
Optional
options: { Optional
Optional
force?: booleanWhether to bypass the actionability checks. Defaults to false
.
Optional
noActions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
navigating to inaccessible pages. Defaults to false
.
Optional
position?: { A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
Optional
strict?: booleanWhen true, the call requires selector to resolve to a single element. If given selector resolves to more than one element, the call throws an exception.
Optional
timeout?: numberMaximum time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via actionTimeout
option in the config, or by using the
browserContext.setDefaultTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
trial?: booleanWhen set, this method only performs the actionability checks and skips the action. Defaults
to false
. Useful to wait until the element is ready for the action without performing it.
Returns when the pageFunction
returns a truthy value, returns that value.
Usage
The frame.waitForFunction(pageFunction[, arg, options]) can be used to observe viewport size change:
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
(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();
})();
To pass an argument to the predicate of frame.waitForFunction
function:
const selector = '.foo';
await frame.waitForFunction(selector => !!document.querySelector(selector), selector);
Function to be evaluated in the page context.
Optional argument to pass to pageFunction
.
Optional
options: PageWaitForFunctionOptionsOptional
Returns when the pageFunction
returns a truthy value, returns that value.
Usage
The frame.waitForFunction(pageFunction[, arg, options]) can be used to observe viewport size change:
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
(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();
})();
To pass an argument to the predicate of frame.waitForFunction
function:
const selector = '.foo';
await frame.waitForFunction(selector => !!document.querySelector(selector), selector);
Function to be evaluated in the page context.
Optional
arg: anyOptional argument to pass to pageFunction
.
Optional
Optional
options: PageWaitForFunctionOptionsOptional
Waits for the required load state to be reached.
This returns when the frame reaches a required load state, load
by default. The navigation must have been
committed when this method is called. If current document has already reached the required state, resolves
immediately.
NOTE Most of the time, this method is not needed because Playwright auto-waits before every action.
Usage
await frame.click('button'); // Click triggers navigation.
await frame.waitForLoadState(); // Waits for 'load' state by default.
Optional
state: "load" | "domcontentloaded" | "networkidle"Optional load state to wait for, defaults to load
. If the state has been already reached while loading current
document, the method resolves immediately. Can be one of:
'load'
- wait for the load
event to be fired.'domcontentloaded'
- wait for the DOMContentLoaded
event to be fired.'networkidle'
- DISCOURAGED wait until there are no network connections for at least 500
ms. Don't use
this method for testing, rely on web assertions to assess readiness instead.Optional
Optional
options: { Optional
Optional
timeout?: numberMaximum operation time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via
navigationTimeout
option in the config, or by using the
browserContext.setDefaultNavigationTimeout(timeout),
browserContext.setDefaultTimeout(timeout),
page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Waits for the frame navigation and returns the main resource response. In case of multiple redirects, the
navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
navigation due to History API usage, the navigation will resolve with null
.
Usage
This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly cause the frame to navigate. Consider this example:
// Start waiting for navigation before clicking. Note no await.
const navigationPromise = page.waitForNavigation();
await page.getByText('Navigate after timeout').click();
await navigationPromise;
NOTE Usage of the History API to change the URL is considered a navigation.
Optional
options: { Optional
Optional
timeout?: numberMaximum operation time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via
navigationTimeout
option in the config, or by using the
browserContext.setDefaultNavigationTimeout(timeout),
browserContext.setDefaultTimeout(timeout),
page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
url?: string | RegExp | ((url) => boolean)A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
Optional
waitWhen to consider operation succeeded, defaults to load
. Events can be either:
'domcontentloaded'
- consider operation to be finished when the DOMContentLoaded
event is fired.'load'
- consider operation to be finished when the load
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for
at least 500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started
loading.This method is inherently racy, please use frame.waitForURL(url[, options]) instead.
NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.
Returns when element specified by selector satisfies state
option. Returns null
if waiting for hidden
or
detached
.
NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.
Wait for the selector
to satisfy state
option (either appear/disappear from dom, or become visible/hidden). If
at the moment of calling the method selector
already satisfies the condition, the method will return immediately.
If the selector doesn't satisfy the condition for the timeout
milliseconds, the function will throw.
Usage
This method works across navigations:
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
for (const currentURL of ['https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
const element = await page.mainFrame().waitForSelector('img');
console.log('Loaded image: ' + await element.getAttribute('src'));
}
await browser.close();
})();
A selector to query for.
Optional
options: PageWaitForSelectorOptionsNotHiddenOptional
NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.
Returns when element specified by selector satisfies state
option. Returns null
if waiting for hidden
or
detached
.
NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.
Wait for the selector
to satisfy state
option (either appear/disappear from dom, or become visible/hidden). If
at the moment of calling the method selector
already satisfies the condition, the method will return immediately.
If the selector doesn't satisfy the condition for the timeout
milliseconds, the function will throw.
Usage
This method works across navigations:
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
for (const currentURL of ['https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
const element = await page.mainFrame().waitForSelector('img');
console.log('Loaded image: ' + await element.getAttribute('src'));
}
await browser.close();
})();
A selector to query for.
Optional
options: PageWaitForSelectorOptionsNotHiddenOptional
NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.
Returns when element specified by selector satisfies state
option. Returns null
if waiting for hidden
or
detached
.
NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.
Wait for the selector
to satisfy state
option (either appear/disappear from dom, or become visible/hidden). If
at the moment of calling the method selector
already satisfies the condition, the method will return immediately.
If the selector doesn't satisfy the condition for the timeout
milliseconds, the function will throw.
Usage
This method works across navigations:
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
for (const currentURL of ['https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
const element = await page.mainFrame().waitForSelector('img');
console.log('Loaded image: ' + await element.getAttribute('src'));
}
await browser.close();
})();
A selector to query for.
NOTE Use web assertions that assert visibility or a locator-based locator.waitFor([options]) instead. Read more about locators.
Returns when element specified by selector satisfies state
option. Returns null
if waiting for hidden
or
detached
.
NOTE Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions make the code wait-for-selector-free.
Wait for the selector
to satisfy state
option (either appear/disappear from dom, or become visible/hidden). If
at the moment of calling the method selector
already satisfies the condition, the method will return immediately.
If the selector doesn't satisfy the condition for the timeout
milliseconds, the function will throw.
Usage
This method works across navigations:
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
for (const currentURL of ['https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
const element = await page.mainFrame().waitForSelector('img');
console.log('Loaded image: ' + await element.getAttribute('src'));
}
await browser.close();
})();
A selector to query for.
NOTE Never wait for timeout in production. Tests that wait for time are inherently flaky. Use Locator actions and web assertions that wait automatically.
Waits for the given timeout
in milliseconds.
Note that frame.waitForTimeout()
should only be used for debugging. Tests using the timer in production are going
to be flaky. Use signals such as network events, selectors becoming visible and others instead.
A timeout to wait for
Waits for the frame to navigate to the given URL.
Usage
await frame.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation
await frame.waitForURL('**/target.html');
A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
Optional
options: { Optional
Optional
timeout?: numberMaximum operation time in milliseconds. Defaults to 0
- no timeout. The default value can be changed via
navigationTimeout
option in the config, or by using the
browserContext.setDefaultNavigationTimeout(timeout),
browserContext.setDefaultTimeout(timeout),
page.setDefaultNavigationTimeout(timeout)
or page.setDefaultTimeout(timeout) methods.
Optional
waitWhen to consider operation succeeded, defaults to load
. Events can be either:
'domcontentloaded'
- consider operation to be finished when the DOMContentLoaded
event is fired.'load'
- consider operation to be finished when the load
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for
at least 500
ms. Don't use this method for testing, rely on web assertions to assess readiness instead.'commit'
- consider operation to be finished when network response is received and the document started
loading.Generated using TypeDoc
At every point of time, page exposes its current frame tree via the page.mainFrame() and frame.childFrames() methods.
Frame object's lifecycle is controlled by three events, dispatched on the page object:
An example of dumping frame tree: