Page
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:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://example.com");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
browser.close();
}
}
}
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:
page.onLoad(p -> System.out.println("Page loaded!"));
To unsubscribe from events use the removeListener
method:
Consumer<Request> logRequest = interceptedRequest -> {
System.out.println("A request was made: " + interceptedRequest.url());
};
page.onRequest(logRequest);
// Sometime later...
page.offRequest(logRequest);
Methods
addInitScript
Added in: v1.8Adds 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:
// preload.js
Math.random = () => 42;
// In your playwright script, assuming the preload.js file is in same directory
page.addInitScript(Paths.get("./preload.js"));
The order of evaluation of multiple scripts installed via BrowserContext.addInitScript() and Page.addInitScript() is not defined.
Arguments
Returns
addLocatorHandler
Added in: v1.42When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.
This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
Things to keep in mind:
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of your normal test flow, instead of using Page.addLocatorHandler().
- Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
- After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You can opt-out of this behavior with
noWaitAfter
. - The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
- You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.
Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.
For example, consider a test that calls Locator.focus() followed by Keyboard.press(). If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use Locator.press() instead to avoid this problem.
Another example is a series of mouse actions, where Mouse.move() is followed by Mouse.down(). Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions like Locator.click() that do not rely on the state being unchanged by a handler.
Usage
An example that closes a "Sign up to the newsletter" dialog when it appears:
// Setup the handler.
page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () => {
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click();
});
// Write the test as usual.
page.goto("https://example.com");
page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
An example that skips the "Confirm your security details" page when it is shown:
// Setup the handler.
page.addLocatorHandler(page.getByText("Confirm your security details")), () => {
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click();
});
// Write the test as usual.
page.goto("https://example.com");
page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
An example with a custom callback on every actionability check. It uses a <body>
locator that is always visible, so the handler is called before every actionability check. It is important to specify noWaitAfter
, because the handler does not hide the <body>
element.
// Setup the handler.
page.addLocatorHandler(page.locator("body")), () => {
page.evaluate("window.removeObstructionsForTestIfNeeded()");
}, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true));
// Write the test as usual.
page.goto("https://example.com");
page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting times
:
page.addLocatorHandler(page.getByLabel("Close"), locator => {
locator.click();
}, new Page.AddLocatorHandlerOptions().setTimes(1));
Arguments
-
Locator that triggers the handler.
-
Function that should be run once
locator
appears. This function should get rid of the element that blocks actions like click. -
options
Page.AddLocatorHandlerOptions
(optional)-
setNoWaitAfter
boolean (optional) Added in: v1.44#By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.
-
setTimes
int (optional) Added in: v1.44#Specifies the maximum number of times this handler should be called. Unlimited by default.
-
Returns
addScriptTag
Added in: v1.8Adds 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.
Usage
Page.addScriptTag();
Page.addScriptTag(options);
Arguments
options
Page.AddScriptTagOptions
(optional)-
Raw JavaScript content to be injected into frame.
-
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. -
Script type. Use 'module' in order to load a Javascript ES6 module. See script for more details.
-
URL of a script to be added.
-
Returns
addStyleTag
Added in: v1.8Adds 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.
Usage
Page.addStyleTag();
Page.addStyleTag(options);
Arguments
options
Page.AddStyleTagOptions
(optional)
Returns
bringToFront
Added in: v1.8Brings page to front (activates tab).
Usage
Page.bringToFront();
Returns
close
Added in: v1.8If runBeforeUnload
is false
, does not run any unload handlers and waits for the page to be closed. If 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.
if runBeforeUnload
is passed as true, a beforeunload
dialog might be summoned and should be handled manually via Page.onDialog(handler) event.
Usage
Page.close();
Page.close(options);
Arguments
options
Page.CloseOptions
(optional)-
setReason
String (optional) Added in: v1.40#The reason to be reported to the operations interrupted by the page closure.
-
setRunBeforeUnload
boolean (optional)#Defaults to
false
. Whether to run the before unload page handlers.
-
Returns
content
Added in: v1.8Gets the full HTML contents of the page, including the doctype.
Usage
Page.content();
Returns
context
Added in: v1.8Get the browser context that the page belongs to.
Usage
Page.context();
Returns
dragAndDrop
Added in: v1.13This 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
page.dragAndDrop("#source", '#target');
// or specify exact positions relative to the top-left corners of the elements:
page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions()
.setSourcePosition(34, 7).setTargetPosition(10, 20));
Arguments
-
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.
-
options
Page.DragAndDropOptions
(optional)-
Whether to bypass the actionability checks. Defaults to
false
. -
setNoWaitAfter
boolean (optional)#Actions 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
. -
setSourcePosition
SourcePosition (optional) Added in: v1.14#Clicks 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.
-
setStrict
boolean (optional) Added in: v1.14#When 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.
-
setTargetPosition
TargetPosition (optional) Added in: v1.14#Drops 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.
-
Maximum time in milliseconds. Defaults to
30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.setDefaultTimeout() or Page.setDefaultTimeout() methods. -
When 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
emulateMedia
Added in: v1.8This method changes the CSS media type
through the media
argument, and/or the 'prefers-colors-scheme'
media feature, using the colorScheme
argument.
Usage
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT));
page.evaluate("() => matchMedia('screen').matches");
// → false
page.evaluate("() => matchMedia('print').matches");
// → true
page.emulateMedia(new Page.EmulateMediaOptions());
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches");
// → true
page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
// → false
page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches");
// → false
Arguments
options
Page.EmulateMediaOptions
(optional)-
setColorScheme
null |enum ColorScheme { LIGHT, DARK, NO_PREFERENCE }
(optional) Added in: v1.9#Emulates
'prefers-colors-scheme'
media feature, supported values are'light'
,'dark'
,'no-preference'
. Passingnull
disables color scheme emulation. -
setForcedColors
null |enum ForcedColors { ACTIVE, NONE }
(optional) Added in: v1.15#Emulates
'forced-colors'
media feature, supported values are'active'
and'none'
. Passingnull
disables forced colors emulation. -
setMedia
null |enum Media { SCREEN, PRINT }
(optional) Added in: v1.9#Changes the CSS media type of the page. The only allowed values are
'screen'
,'print'
andnull
. Passingnull
disables CSS media emulation. -
setReducedMotion
null |enum ReducedMotion { REDUCE, NO_PREFERENCE }
(optional) Added in: v1.12#Emulates
'prefers-reduced-motion'
media feature, supported values are'reduce'
,'no-preference'
. Passingnull
disables reduced motion emulation.
-
Returns
evaluate
Added in: v1.8Returns the value of the expression
invocation.
If the function passed to the Page.evaluate() returns a Promise, then Page.evaluate() would wait for the promise to resolve and return its value.
If the function passed to the Page.evaluate() returns a non-Serializable value, then 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 expression
:
Object result = page.evaluate("([x, y]) => {\n" +
" return Promise.resolve(x * y);\n" +
"}", Arrays.asList(7, 8));
System.out.println(result); // prints "56"
A string can also be passed in instead of a function:
System.out.println(page.evaluate("1 + 2")); // prints "3"
ElementHandle instances can be passed as an argument to the Page.evaluate():
ElementHandle bodyHandle = page.evaluate("document.body");
String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello"));
bodyHandle.dispose();
Arguments
-
JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
-
arg
EvaluationArgument (optional)#Optional argument to pass to
expression
.
Returns
evaluateHandle
Added in: v1.8Returns the value of the expression
invocation as a JSHandle.
The only difference between Page.evaluate() and Page.evaluateHandle() is that Page.evaluateHandle() returns JSHandle.
If the function passed to the Page.evaluateHandle() returns a Promise, then Page.evaluateHandle() would wait for the promise to resolve and return its value.
Usage
// Handle for the window object.
JSHandle aWindowHandle = page.evaluateHandle("() => Promise.resolve(window)");
A string can also be passed in instead of a function:
JSHandle aHandle = page.evaluateHandle("document"); // Handle for the "document".
JSHandle instances can be passed as an argument to the Page.evaluateHandle():
JSHandle aHandle = page.evaluateHandle("() => document.body");
JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello"));
System.out.println(resultHandle.jsonValue());
resultHandle.dispose();
Arguments
-
JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
-
arg
EvaluationArgument (optional)#Optional argument to pass to
expression
.
Returns
exposeBinding
Added in: v1.8The method adds a function called name
on the window
object of every frame in this page. When called, the function executes callback
and returns a Promise which resolves to the return value of callback
. If the callback
returns a Promise, it will be awaited.
The first argument of the callback
function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }
.
See BrowserContext.exposeBinding() for the context-wide version.
Functions installed via Page.exposeBinding() survive navigations.
Usage
An example of exposing page URL to all frames in a page:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch({ headless: false });
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.exposeBinding("pageURL", (source, args) -> source.page().url());
page.setContent("<script>\n" +
" async function onClick() {\n" +
" document.querySelector('div').textContent = await window.pageURL();\n" +
" }\n" +
"</script>\n" +
"<button onclick=\"onClick()\">Click me</button>\n" +
"<div></div>");
page.click("button");
}
}
}
Arguments
-
Name of the function on the window object.
-
callback
BindingCallback
#Callback function that will be called in the Playwright's context.
-
options
Page.ExposeBindingOptions
(optional)
Returns
exposeFunction
Added in: v1.8The method adds a function called name
on the window
object of every frame in the page. When called, the function executes callback
and returns a Promise which resolves to the return value of callback
.
If the callback
returns a Promise, it will be awaited.
See BrowserContext.exposeFunction() for context-wide exposed function.
Functions installed via Page.exposeFunction() survive navigations.
Usage
An example of adding a sha256
function to the page:
import com.microsoft.playwright.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch({ headless: false });
Page page = browser.newPage();
page.exposeFunction("sha256", args -> {
String text = (String) args[0];
MessageDigest crypto;
try {
crypto = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
return null;
}
byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(token);
});
page.setContent("<script>\n" +
" async function onClick() {\n" +
" document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
" }\n" +
"</script>\n" +
"<button onclick=\"onClick()\">Click me</button>\n" +
"<div></div>\n");
page.click("button");
}
}
}
Arguments
-
Name of the function on the window object
-
callback
FunctionCallback
#Callback function which will be called in Playwright's context.
Returns
frame
Added in: v1.8Returns frame matching the specified criteria. Either name
or url
must be specified.
Usage
Frame frame = page.frame("frame-name");
Frame frame = page.frameByUrl(Pattern.compile(".*domain.*");
Arguments
Returns
frameByUrl
Added in: v1.9Returns frame with matching URL.
Usage
Page.frameByUrl(url);
Arguments
-
url
String | Pattern | Predicate<String>#A glob pattern, regex pattern or predicate receiving frame's
url
as a [URL] object.
Returns
frameLocator
Added in: v1.17When 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">
:
Locator locator = page.frameLocator("#my-iframe").getByText("Submit");
locator.click();
Arguments
Returns
frames
Added in: v1.8An array of all frames attached to the page.
Usage
Page.frames();
Returns
getByAltText
Added in: v1.27Allows locating elements by their alt text.
Usage
For example, this method will find the image by alt text "Playwright logo":
<img alt='Playwright logo'>
page.getByAltText("Playwright logo").click();
Arguments
-
Text to locate the element for.
-
options
Page.GetByAltTextOptions
(optional)
Returns
getByLabel
Added in: v1.27Allows 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">
page.getByLabel("Username").fill("john");
page.getByLabel("Password").fill("secret");
Arguments
-
Text to locate the element for.
-
options
Page.GetByLabelOptions
(optional)
Returns
getByPlaceholder
Added in: v1.27Allows 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:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
Arguments
-
Text to locate the element for.
-
options
Page.GetByPlaceholderOptions
(optional)
Returns
getByRole
Added in: v1.27Allows 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:
assertThat(page
.getByRole(AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Sign up")))
.isVisible();
page.getByRole(AriaRole.CHECKBOX,
new Page.GetByRoleOptions().setName("Subscribe"))
.check();
page.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName(
Pattern.compile("submit", Pattern.CASE_INSENSITIVE)))
.click();
Arguments
-
role
enum AriaRole { ALERT, ALERTDIALOG, APPLICATION, ARTICLE, BANNER, BLOCKQUOTE, BUTTON, CAPTION, CELL, CHECKBOX, CODE, COLUMNHEADER, COMBOBOX, COMPLEMENTARY, CONTENTINFO, DEFINITION, DELETION, DIALOG, DIRECTORY, DOCUMENT, EMPHASIS, FEED, FIGURE, FORM, GENERIC, GRID, GRIDCELL, GROUP, HEADING, IMG, INSERTION, LINK, LIST, LISTBOX, LISTITEM, LOG, MAIN, MARQUEE, MATH, METER, MENU, MENUBAR, MENUITEM, MENUITEMCHECKBOX, MENUITEMRADIO, NAVIGATION, NONE, NOTE, OPTION, PARAGRAPH, PRESENTATION, PROGRESSBAR, RADIO, RADIOGROUP, REGION, ROW, ROWGROUP, ROWHEADER, SCROLLBAR, SEARCH, SEARCHBOX, SEPARATOR, SLIDER, SPINBUTTON, STATUS, STRONG, SUBSCRIPT, SUPERSCRIPT, SWITCH, TAB, TABLE, TABLIST, TABPANEL, TERM, TEXTBOX, TIME, TIMER, TOOLBAR, TOOLTIP, TREE, TREEGRID, TREEITEM }
#Required aria role.
-
options
Page.GetByRoleOptions
(optional)-
setChecked
boolean (optional)#An attribute that is usually set by
aria-checked
or native<input type=checkbox>
controls.Learn more about
aria-checked
. -
setDisabled
boolean (optional)#An attribute that is usually set by
aria-disabled
ordisabled
.noteUnlike most other attributes,
disabled
is inherited through the DOM hierarchy. Learn more aboutaria-disabled
. -
setExact
boolean (optional) Added in: v1.28#Whether
name
is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored whenname
is a regular expression. Note that exact match still trims whitespace. -
setExpanded
boolean (optional)#An attribute that is usually set by
aria-expanded
.Learn more about
aria-expanded
. -
setIncludeHidden
boolean (optional)#Option 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
. -
A number attribute that is usually present for roles
heading
,listitem
,row
,treeitem
, with default values for<h1>-<h6>
elements.Learn more about
aria-level
. -
setName
String | Pattern (optional)#Option 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.
-
setPressed
boolean (optional)#An attribute that is usually set by
aria-pressed
.Learn more about
aria-pressed
. -
setSelected
boolean (optional)#An attribute that is usually set by
aria-selected
.Learn more about
aria-selected
.
-
Returns
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.
getByTestId
Added in: v1.27Locate 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:
page.getByTestId("directions").click();
Arguments
Returns
Details
By default, the data-testid
attribute is used as a test id. Use Selectors.setTestIdAttribute() to configure a different test id attribute if necessary.
getByText
Added in: v1.27Allows locating elements that contain given text.
See also Locator.filter() 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", new Page.GetByTextOptions().setExact(true))
// Matches both <div>s
page.getByText(Pattern.compile("Hello"))
// Matches second <div>
page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
Arguments
-
Text to locate the element for.
-
options
Page.GetByTextOptions
(optional)
Returns
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">
.
getByTitle
Added in: v1.27Allows 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:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");
Arguments
-
Text to locate the element for.
-
options
Page.GetByTitleOptions
(optional)
Returns
goBack
Added in: v1.8Returns 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.
Usage
Page.goBack();
Page.goBack(options);
Arguments
options
Page.GoBackOptions
(optional)-
Maximum operation time in milliseconds, defaults to 30 seconds, pass
0
to disable timeout. The default value can be changed by using the BrowserContext.setDefaultNavigationTimeout(), BrowserContext.setDefaultTimeout(), Page.setDefaultNavigationTimeout() or Page.setDefaultTimeout() methods. -
setWaitUntil
enum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }
(optional)#When to consider operation succeeded, defaults to
load
. Events can be either:'domcontentloaded'
- consider operation to be finished when theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
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.
-
Returns
goForward
Added in: v1.8Returns 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.
Usage
Page.goForward();
Page.goForward(options);
Arguments
options
Page.GoForwardOptions
(optional)-
Maximum operation time in milliseconds, defaults to 30 seconds, pass
0
to disable timeout. The default value can be changed by using the BrowserContext.setDefaultNavigationTimeout(), BrowserContext.setDefaultTimeout(), Page.setDefaultNavigationTimeout() or Page.setDefaultTimeout() methods. -
setWaitUntil
enum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }
(optional)#When to consider operation succeeded, defaults to
load
. Events can be either:'domcontentloaded'
- consider operation to be finished when theDOMContentLoaded
event is fired.'load'
- consider operation to be finished when theload
event is fired.'networkidle'
- DISCOURAGED consider operation to be finished when there are no network connections for at least500
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.
-
Returns
isClosed
Added in: v1.8Indicates that the page has been closed.
Usage
Page.isClosed();
Returns
locator
Added in: v1.14The 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.
Usage
Page.locator(selector);
Page.locator(selector, options);
Arguments
-
A selector to use when resolving DOM element.
-
options
Page.LocatorOptions
(optional)-
Narrows down the results of the method to those which contain elements matching this relative locator. For example,
article
that hastext=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 hasdiv
in<article><content><div>Playwright</div></content></article>
. However, looking forcontent
that hasarticle div
will fail, because the inner locator must be relative and should not use any elements outside thecontent
.Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.
-
setHasNot
Locator (optional) Added in: v1.33#Matches 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 havediv
matches<article><span>Playwright</span></article>
.Note that outer and inner locators must belong to the same frame. Inner locator must not contain FrameLocators.
-
setHasNotText
String | Pattern (optional) Added in: v1.33#Matches 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.
-
setHasText
String | Pattern (optional)#Matches 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>
.
-
Returns