waitUntil
<[WaitUntilState]<"load"|"domcontentloaded"|"networkidle"|"commit">>
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'
- consider operation to be finished when there are no network connections for at least500
ms.'commit'
- consider operation to be finished when network response is received and the document started loading.
timeout
<[float]>
Maximum operation time in milliseconds, defaults to 30 seconds, pass 0
to disable timeout.
The default value can be changed by using the
[method: BrowserContext.setDefaultNavigationTimeout
],
[method: BrowserContext.setDefaultTimeout
],
[method: Page.setDefaultNavigationTimeout
] or
[method: Page.setDefaultTimeout
] methods.
timeout
<[float]>
maximum time to wait for in milliseconds. Defaults to 30000
(30 seconds). Pass 0
to disable timeout. The default
value can be changed by using the [method: BrowserContext.setDefaultTimeout
].
strict
<[boolean]>
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.
timeout
<[float]>
Maximum time in milliseconds, defaults to 30 seconds, pass 0
to disable timeout. The default value can be changed by
using the [method: BrowserContext.setDefaultTimeout
] or
[method: Page.setDefaultTimeout
] methods.
noWaitAfter
<[boolean]>
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
.
force
<[boolean]>
Whether to bypass the actionability checks. Defaults to false
.
selector
<[string]>
A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
source
<[string]>
A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
target
<[string]>
A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.
position
<[Object]>x
<[float]>y
<[float]>
A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
modifiers
<[Array]<[KeyboardModifier]<"Alt"|"Control"|"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.
button
<[MouseButton]<"left"|"right"|"middle">>
Defaults to left
.
files
<[path]|[Array]<[path]>|[Object]|[Array]<[Object]>>name
<[string]> File namemimeType
<[string]> File typebuffer
<[Buffer]> File content
delay
<[float]>
Time to wait between mousedown
and mouseup
in milliseconds. Defaults to 0.
clickCount
<[int]>
defaults to 1. See [UIEvent.detail].
trial
<[boolean]>
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.
sourcePosition
<[Object]>x
<[float]>y
<[float]>
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.
targetPosition
<[Object]>x
<[float]>y
<[float]>
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.
- langs:
- alias-csharp: checkedState
checked
<[boolean]>
Whether to check or uncheck the checkbox.
selector
<[string]>
A selector to query for.
selector
<[string]>
A selector to use when resolving DOM element.
state
<[WaitForSelectorState]<"attached"|"detached"|"visible"|"hidden">>
Defaults to 'visible'
. Can be either:
'attached'
- wait for element to be present in DOM.'detached'
- wait for element to not be present in DOM.'visible'
- wait for element to have non-empty bounding box and novisibility:hidden
. Note that element without any content or withdisplay:none
has an empty bounding box and is not considered visible.'hidden'
- wait for element to be either detached from DOM, or have an empty bounding box orvisibility:hidden
. This is opposite to the'visible'
option.
- langs: js, python
polling
<[float]|"raf">
If [option: polling
] is 'raf'
, then [param: expression
] is constantly executed in requestAnimationFrame
callback. If [option: polling
] is a number, then it is treated as an interval in milliseconds at which the function
would be executed. Defaults to raf
.
- langs: csharp, java
pollingInterval
<[float]>
If specified, then it is treated as an interval in milliseconds at which the function would be executed. By default if the option is not specified [param: expression
] is executed in requestAnimationFrame
callback.
- langs: js, python
ignoreDefaultArgs
<[boolean]|[Array]<[string]>>
If true
, Playwright does not pass its own configurations args and only uses the ones from [option: args
]. If an
array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to false
.
- langs: csharp, java
ignoreDefaultArgs
<[Array]<[string]>>
If true
, Playwright does not pass its own configurations args and only uses the ones from [option: args
].
Dangerous option; use with care.
- langs: csharp, java
ignoreAllDefaultArgs
<[boolean]>
If true
, Playwright does not pass its own configurations args and only uses the ones from [option: args
].
Dangerous option; use with care. Defaults to false
.
proxy
<[Object]>server
<[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for examplehttp://myproxy.com:3128
orsocks5://myproxy.com:3128
. Short formmyproxy.com:3128
is considered an HTTP proxy.bypass
?<[string]> Optional comma-separated domains to bypass proxy, for example".com, chromium.org, .domain.com"
.username
?<[string]> Optional username to use if HTTP proxy requires authentication.password
?<[string]> Optional password to use if HTTP proxy requires authentication.
Network proxy settings.
- langs: csharp, java
env
<[Object]<[string], [string]>>
Specify environment variables that will be visible to the browser. Defaults to process.env
.
- langs: js, python
env
<[Object]<[string], [string]|[float]|[boolean]>>
Specify environment variables that will be visible to the browser. Defaults to process.env
.
- langs: js, python
storageState
<[path]|[Object]>cookies
<[Array]<[Object]>> cookies to set for contextname
<[string]>value
<[string]>domain
<[string]> domain and path are requiredpath
<[string]> domain and path are requiredexpires
<[float]> Unix time in seconds.httpOnly
<[boolean]>secure
<[boolean]>sameSite
<[SameSiteAttribute]<"Strict"|"Lax"|"None">> sameSite flag
origins
<[Array]<[Object]>> localStorage to set for contextorigin
<[string]>localStorage
<[Array]<[Object]>>name
<[string]>value
<[string]>
Populates context with given storage state. This option can be used to initialize context with logged-in information
obtained via [method: BrowserContext.storageState
]. Either a path to the file with saved storage, or an object with the following fields:
- langs: csharp, java
storageState
<[string]>
Populates context with given storage state. This option can be used to initialize context with logged-in information
obtained via [method: BrowserContext.storageState
].
- langs: csharp, java
storageStatePath
<[path]>
Populates context with given storage state. This option can be used to initialize context with logged-in information
obtained via [method: BrowserContext.storageState
]. Path to the file with saved storage state.
path
<[path]>
The file path to save the storage state to. If [option: path
] is a relative path, then it is resolved relative to
current working directory. If no path is provided, storage
state is still returned, but won't be saved to the disk.
acceptDownloads
<[boolean]>
Whether to automatically download all the attachments. Defaults to true
where all the downloads are accepted.
ignoreHTTPSErrors
<[boolean]>
Whether to ignore HTTPS errors when sending network requests. Defaults to false
.
bypassCSP
<[boolean]>
Toggles bypassing page's Content-Security-Policy.
baseURL
<[string]>
When using [method: Page.goto
], [method: Page.route
], [method: Page.waitForURL
], [method: Page.waitForRequest
], or [method: Page.waitForResponse
] it takes the base URL in consideration by using the URL()
constructor for building the corresponding URL. Examples:
- baseURL:
http://localhost:3000
and navigating to/bar.html
results inhttp://localhost:3000/bar.html
- baseURL:
http://localhost:3000/foo/
and navigating to./bar.html
results inhttp://localhost:3000/foo/bar.html
- baseURL:
http://localhost:3000/foo
(without trailing slash) and navigating to./bar.html
results inhttp://localhost:3000/bar.html
- langs: js, java
- alias-java: viewportSize
viewport
<[null]|[Object]>width
<[int]> page width in pixels.height
<[int]> page height in pixels.
Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. null
disables the default viewport.
- langs: csharp
- alias-csharp: viewportSize
viewport
<[null]|[Object]>width
<[int]> page width in pixels.height
<[int]> page height in pixels.
Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use ViewportSize.NoViewport
to disable the default viewport.
- langs:
- alias-java: screenSize
- alias-csharp: screenSize
screen
<[Object]>width
<[int]> page width in pixels.height
<[int]> page height in pixels.
Emulates consistent window screen size available inside web page via window.screen
. Is only used when the
[option: viewport
] is set.
url
<[string]>
Target URL.
- langs: js, python
params
<[Object]<[string], [string]|[float]|[boolean]>>
Query parameters to be sent with the URL.
- langs: csharp
params
<[Object]<[string], [Serializable]>>
Query parameters to be sent with the URL.
- langs: java
options
?<[RequestOptions]>
Optional request parameters.
- langs: js, python, csharp
headers
<[Object]<[string], [string]>>
Allows to set HTTP headers.
- langs: js, python, csharp
timeout
<[float]>
Request timeout in milliseconds. Defaults to 30000
(30 seconds). Pass 0
to disable timeout.
- langs: js, python, csharp
failOnStatusCode
<[boolean]>
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
- langs: js, python
form
<[Object]<[string], [string]|[float]|[boolean]>>
Provides an object that will be serialized as html form using application/x-www-form-urlencoded
encoding and sent as
this request body. If this parameter is specified content-type
header will be set to application/x-www-form-urlencoded
unless explicitly provided.
- langs: csharp
form
<[FormData]>
Provides an object that will be serialized as html form using application/x-www-form-urlencoded
encoding and sent as
this request body. If this parameter is specified content-type
header will be set to application/x-www-form-urlencoded
unless explicitly provided.
An instance of [FormData] can be created via [method: APIRequestContext.createFormData
].
- langs: js, python
multipart
<[Object]<[string], [string]|[float]|[boolean]|[ReadStream]|[Object]>>name
<[string]> File namemimeType
<[string]> File typebuffer
<[Buffer]> File content
Provides an object that will be serialized as html form using multipart/form-data
encoding and sent as
this request body. If this parameter is specified content-type
header will be set to multipart/form-data
unless explicitly provided. File values can be passed either as fs.ReadStream
or as file-like object containing file name, mime-type and its content.
- langs: csharp
multipart
<[FormData]>
Provides an object that will be serialized as html form using multipart/form-data
encoding and sent as
this request body. If this parameter is specified content-type
header will be set to multipart/form-data
unless explicitly provided. File values can be passed either as fs.ReadStream
or as file-like object containing file name, mime-type and its content.
An instance of [FormData] can be created via [method: APIRequestContext.createFormData
].
- langs: js, python, csharp
data
<[string]|[Buffer]|[Serializable]>
Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
and content-type
header will be set to application/json
if not explicitly set. Otherwise the content-type
header will be
set to application/octet-stream
if not explicitly set.
- langs: js, python, csharp
ignoreHTTPSErrors
<[boolean]>
Whether to ignore HTTPS errors when sending network requests. Defaults to false
.
- langs: js, python, csharp
maxRedirects
<[int]>
Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded.
Defaults to 20
. Pass 0
to not follow redirects.
expression
<[string]>
JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
- langs: js
pageFunction
<[function]|[string]>
Function to be evaluated in the page context.
- langs: js
pageFunction
<[function]([Element])>
Function to be evaluated in the page context.
- langs: js
pageFunction
<[function]([Array]<[Element]>)>
Function to be evaluated in the page context.
- langs: js
pageFunction
<[function]|[string]>
Function to be evaluated in the worker context.
- langs: js
pageFunction
<[function]|[Electron]>
Function to be evaluated in the worker context.
- langs: python
viewport
<[null]|[Object]>width
<[int]> page width in pixels.height
<[int]> page height in pixels.
Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. no_viewport
disables the fixed viewport.
- langs: python
noViewport
<[boolean]>
Does not enforce fixed viewport, allows resizing window in the headed mode.
userAgent
<[string]>
Specific user agent to use in this context.
deviceScaleFactor
<[float]>
Specify device scale factor (can be thought of as dpr). Defaults to 1
.
isMobile
<[boolean]>
Whether the meta viewport
tag is taken into account and touch events are enabled. Defaults to false
. Not supported
in Firefox.
hasTouch
<[boolean]>
Specifies if viewport supports touch events. Defaults to false.
javaScriptEnabled
<[boolean]>
Whether or not to enable JavaScript in the context. Defaults to true
.
timezoneId
<[string]>
Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs.
geolocation
<[Object]>latitude
<[float]> Latitude between -90 and 90.longitude
<[float]> Longitude between -180 and 180.accuracy
?<[float]> Non-negative accuracy value. Defaults to0
.
locale
<[string]>
Specify user locale, for example en-GB
, de-DE
, etc. Locale will affect navigator.language
value, Accept-Language
request header value as well as number and date formatting rules.
permissions
<[Array]<[string]>>
A list of permissions to grant to all pages in this context. See
[method: BrowserContext.grantPermissions
] for more details.
extraHTTPHeaders
<[Object]<[string], [string]>>
An object containing additional HTTP headers to be sent with every request.
offline
<[boolean]>
Whether to emulate network being offline. Defaults to false
.
httpCredentials
<[Object]>username
<[string]>password
<[string]>
Credentials for HTTP authentication.
- langs: js, java
colorScheme
<null|[ColorScheme]<"light"|"dark"|"no-preference">>
Emulates 'prefers-colors-scheme'
media feature, supported values are 'light'
, 'dark'
, 'no-preference'
. See
[method: Page.emulateMedia
] for more details. Passing null
resets emulation to system defaults. Defaults to 'light'
.
- langs: csharp, python
colorScheme
<[ColorScheme]<"light"|"dark"|"no-preference"|"null">>
Emulates 'prefers-colors-scheme'
media feature, supported values are 'light'
, 'dark'
, 'no-preference'
. See
[method: Page.emulateMedia
] for more details. Passing 'null'
resets emulation to system defaults. Defaults to 'light'
.
- langs: js, java
reducedMotion
<null|[ReducedMotion]<"reduce"|"no-preference">>
Emulates 'prefers-reduced-motion'
media feature, supported values are 'reduce'
, 'no-preference'
. See [method: Page.emulateMedia
] for more details. Passing null
resets emulation to system defaults. Defaults to 'no-preference'
.
- langs: csharp, python
reducedMotion
<[ReducedMotion]<"reduce"|"no-preference"|"null">>
Emulates 'prefers-reduced-motion'
media feature, supported values are 'reduce'
, 'no-preference'
. See [method: Page.emulateMedia
] for more details. Passing 'null'
resets emulation to system defaults. Defaults to 'no-preference'
.
- langs: js, java
forcedColors
<null|[ForcedColors]<"active"|"none">>
Emulates 'forced-colors'
media feature, supported values are 'active'
, 'none'
. See [method: Page.emulateMedia
] for more details. Passing null
resets emulation to system defaults. Defaults to 'none'
.
- langs: csharp, python
forcedColors
<[ForcedColors]<"active"|"none"|"null">>
Emulates 'forced-colors'
media feature, supported values are 'active'
, 'none'
. See [method: Page.emulateMedia
] for more details. Passing 'null'
resets emulation to system defaults. Defaults to 'none'
.
- langs: js
logger
<[Logger]>
Logger sink for Playwright logging.
- langs: js
- deprecated: Use [
option: recordVideo
] instead.
videosPath
<[path]>
- langs: js
- deprecated: Use [
option: recordVideo
] instead.
videoSize
<[Object]>width
<[int]> Video frame width.height
<[int]> Video frame height.
- langs: js
recordHar
<[Object]>omitContent
?<[boolean]> Optional setting to control whether to omit request content from the HAR. Defaults tofalse
. Deprecated, usecontent
policy instead.content
?<[HarContentPolicy]<"omit"|"embed"|"attach">> Optional setting to control resource content management. Ifomit
is specified, content is not persisted. Ifattach
is specified, resources are persisted as separate files or entries in the ZIP archive. Ifembed
is specified, content is stored inline the HAR file as per HAR specification. Defaults toattach
for.zip
output files and toembed
for all other file extensions.path
<[path]> Path on the filesystem to write the HAR file to. If the file name ends with.zip
,content: 'attach'
is used by default.mode
?<[HarMode]<"full"|"minimal">> When set tominimal
, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults tofull
.urlFilter
?<[string]|[RegExp]> A glob or regex pattern to filter requests that are stored in the HAR. When a [option: baseURL
] via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.
Enables HAR recording for all pages into recordHar.path
file. If not
specified, the HAR is not recorded. Make sure to await [method: BrowserContext.close
] for the HAR to be
saved.
- langs: csharp, java, python
- alias-python: record_har_path
recordHarPath
<[path]>
Enables HAR recording for all pages into the
specified HAR file on the filesystem. If not specified, the HAR is not recorded. Make sure to
call [method: BrowserContext.close
] for the HAR to be saved.
- langs: csharp, java, python
- alias-python: record_har_omit_content
recordHarOmitContent
?<[boolean]>
Optional setting to control whether to omit request content from the HAR. Defaults to false
.
- langs: csharp, java, python
- alias-python: record_har_content
recordHarContent
?<[HarContentPolicy]<"omit"|"embed"|"attach">>
Optional setting to control resource content management. If omit
is specified, content is not persisted. If attach
is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. Defaults to embed
, which stores content inline the HAR file as per HAR specification.
- langs: csharp, java, python
- alias-python: record_har_mode
recordHarMode
?<[HarMode]<"full"|"minimal">>
When set to minimal
, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to full
.
- langs: csharp, java, python
- alias-python: record_har_url_filter
recordHarUrlFilter
?<[string]|[RegExp]>
- langs: js
recordVideo
<[Object]>dir
<[path]> Path to the directory to put videos into.size
?<[Object]> Optional dimensions of the recorded videos. If not specified the size will be equal toviewport
scaled down to fit into 800x800. Ifviewport
is not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.width
<[int]> Video frame width.height
<[int]> Video frame height.
Enables video recording for all pages into recordVideo.dir
directory. If not specified videos are not recorded. Make
sure to await [method: BrowserContext.close
] for videos to be saved.
- langs: csharp, java, python
- alias-python: record_video_dir
recordVideoDir
<[path]>
Enables video recording for all pages into the specified directory. If not specified videos are
not recorded. Make sure to call [method: BrowserContext.close
] for videos to be saved.
- langs: csharp, java, python
- alias-python: record_video_size
recordVideoSize
<[Object]> Ifviewport
is not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.width
<[int]> Video frame width.height
<[int]> Video frame height.
Dimensions of the recorded videos. If not specified the size will be equal to viewport
scaled down to fit into 800x800. If viewport
is not configured explicitly the video size defaults to 800x450.
Actual picture of each page will be scaled down if necessary to fit the specified size.
proxy
<[Object]>server
<[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for examplehttp://myproxy.com:3128
orsocks5://myproxy.com:3128
. Short formmyproxy.com:3128
is considered an HTTP proxy.bypass
?<[string]> Optional comma-separated domains to bypass proxy, for example".com, chromium.org, .domain.com"
.username
?<[string]> Optional username to use if HTTP proxy requires authentication.password
?<[string]> Optional password to use if HTTP proxy requires authentication.
Network proxy settings to use with this context.
:::note
For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all
contexts override the proxy, global proxy will be never used and can be any string, for example
launch({ proxy: { server: 'http://per-context' } })
.
:::
strictSelectors
<[boolean]>
If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors that imply single target DOM element will throw when more than one element matches the selector. This option does not affect any Locator APIs (Locators are always strict). See [Locator] to learn more about the strict mode.
serviceWorkers
<[ServiceWorkerPolicy]<"allow"|"block">>
Whether to allow sites to register Service workers. Defaults to 'allow'
.
'allow'
: Service Workers can be registered.'block'
: Playwright will block all registration of Service Workers.
- langs: java, js, csharp
values
<[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>>value
?<[string]> Matches byoption.value
. Optional.label
?<[string]> Matches byoption.label
. Optional.index
?<[int]> Matches by the index. Optional.
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.
url
<[string]|[RegExp]|[function]([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.
- langs: js, python, java
event
<[string]>
Event name, same one typically passed into *.on(event)
.
state
?<[LoadState]<"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 theload
event to be fired.'domcontentloaded'
- wait for theDOMContentLoaded
event to be fired.'networkidle'
- wait until there are no network connections for at least500
ms.
- langs: java
callback
<[Runnable]>
Callback that performs the action triggering the event.
- langs: csharp
action
<[Func]>
Action that triggers the event.
- langs: python
element
?<[ElementHandle]|[Array]<[ElementHandle]>>
Option elements to select. Optional.
- langs: python
index
?<[int]|[Array]<[int]>>
Options to select by index. Optional.
- langs: python
value
?<[string]|[Array]<[string]>>
Options to select by value. If the <select>
has the multiple
attribute, all given options are selected, otherwise
only the first option matching one of the passed options is selected. Optional.
- langs: python
label
?<[string]|[Array]<[string]>>
Options to select by label. If the <select>
has the multiple
attribute, all given options are selected, otherwise
only the first option matching one of the passed options is selected. Optional.
predicate
<[function]>
Receives the event data and resolves to truthy value when the waiting should resolve.
- langs: csharp, java, python
timeout
<[float]>
Maximum time to wait for in milliseconds. Defaults to 30000
(30 seconds). Pass 0
to disable timeout.
The default value can be changed by using the [method: BrowserContext.setDefaultTimeout
].
- langs: js
timeout
<[float]>
Maximum time in milliseconds, defaults to 30 seconds, pass 0
to disable timeout. The default value can be changed by
using the [method: AndroidDevice.setDefaultTimeout
] method.
- langs: js
timeout
<[float]>
Time to retry the assertion for. Defaults to timeout
in TestConfig.expect
.
- langs: java, python, csharp
timeout
<[float]>
Time to retry the assertion for.
- langs: js
maxDiffPixels
<[int]>
An acceptable amount of pixels that could be different. Default is configurable with TestConfig.expect
. Unset by default.
- langs: js
maxDiffPixelRatio
<[float]>
An acceptable ratio of pixels that are different to the total amount of pixels, between 0
and 1
. Default is configurable with TestConfig.expect
. Unset by default.
- langs: js
threshold
<[float]>
An acceptable perceived color difference in the YIQ color space
between the same pixel in compared images, between zero (strict) and one (lax), default is configurable with
TestConfig.expect
. Defaults to 0.2
.
- %%-context-option-acceptdownloads-%%
- %%-context-option-ignorehttpserrors-%%
- %%-context-option-bypasscsp-%%
- %%-context-option-baseURL-%%
- %%-context-option-viewport-%%
- %%-csharp-context-option-viewport-%%
- %%-python-context-option-viewport-%%
- %%-context-option-screen-%%
- %%-python-context-option-no-viewport-%%
- %%-context-option-useragent-%%
- %%-context-option-devicescalefactor-%%
- %%-context-option-ismobile-%%
- %%-context-option-hastouch-%%
- %%-context-option-javascriptenabled-%%
- %%-context-option-timezoneid-%%
- %%-context-option-geolocation-%%
- %%-context-option-locale-%%
- %%-context-option-permissions-%%
- %%-context-option-extrahttpheaders-%%
- %%-context-option-offline-%%
- %%-context-option-httpcredentials-%%
- %%-context-option-colorscheme-%%
- %%-context-option-colorscheme-csharp-python-%%
- %%-context-option-reducedMotion-%%
- %%-context-option-reducedMotion-csharp-python-%%
- %%-context-option-forcedColors-%%
- %%-context-option-forcedColors-csharp-python-%%
- %%-context-option-logger-%%
- %%-context-option-videospath-%%
- %%-context-option-videosize-%%
- %%-context-option-recordhar-%%
- %%-context-option-recordhar-path-%%
- %%-context-option-recordhar-omit-content-%%
- %%-context-option-recordhar-content-%%
- %%-context-option-recordhar-mode-%%
- %%-context-option-recordhar-url-filter-%%
- %%-context-option-recordvideo-%%
- %%-context-option-recordvideo-dir-%%
- %%-context-option-recordvideo-size-%%
- %%-context-option-strict-%%
- %%-context-option-service-worker-policy-%%
args
<[Array]<[string]>>
Additional arguments to pass to the browser instance. The list of Chromium flags can be found here.
channel
<[string]>
Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using Google Chrome and Microsoft Edge.
chromiumSandbox
<[boolean]>
Enable Chromium sandboxing. Defaults to false
.
downloadsPath
<[path]>
If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in is closed.
executablePath
<[path]>
Path to a browser executable to run instead of the bundled one. If [option: executablePath
] is a relative path, then
it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
Firefox or WebKit, use at your own risk.
handleSIGINT
<[boolean]>
Close the browser process on Ctrl-C. Defaults to true
.
handleSIGTERM
<[boolean]>
Close the browser process on SIGTERM. Defaults to true
.
handleSIGHUP
<[boolean]>
Close the browser process on SIGHUP. Defaults to true
.
headless
<[boolean]>
Whether to run browser in headless mode. More details for
Chromium and
Firefox. Defaults to true
unless the
[option: devtools
] option is true
.
- langs: js, python
firefoxUserPrefs
<[Object]<[string], [string]|[float]|[boolean]>>
Firefox user preferences. Learn more about the Firefox user preferences at
about:config
.
- langs: csharp, java
firefoxUserPrefs
<[Object]<[string], [any]>>
Firefox user preferences. Learn more about the Firefox user preferences at
about:config
.
- langs: js
logger
<[Logger]>
Logger sink for Playwright logging.
timeout
<[float]>
Maximum time in milliseconds to wait for the browser instance to start. Defaults to 30000
(30 seconds). Pass 0
to
disable timeout.
tracesDir
<[path]>
If specified, traces are saved into this directory.
devtools
<[boolean]>
Chromium-only Whether to auto-open a Developer Tools panel for each tab. If this option is true
, the
[option: headless
] option will be set false
.
slowMo
<[float]>
Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
- %%-browser-option-args-%%
- %%-browser-option-channel-%%
- %%-browser-option-chromiumsandbox-%%
- %%-browser-option-devtools-%%
- %%-browser-option-downloadspath-%%
- %%-csharp-java-browser-option-env-%%
- %%-js-python-browser-option-env-%%
- %%-browser-option-executablepath-%%
- %%-browser-option-handlesigint-%%
- %%-browser-option-handlesigterm-%%
- %%-browser-option-handlesighup-%%
- %%-browser-option-headless-%%
- %%-browser-option-ignoredefaultargs-%%
- %%-browser-option-proxy-%%
- %%-browser-option-timeout-%%
- %%-browser-option-tracesdir-%%
hasText
<[string]|[RegExp]>
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>
.
has
<[Locator]>
Matches elements containing an element that matches an inner locator. Inner locator is queried against the outer one.
For example, article
that has text=Playwright
matches <article><div>Playwright</div></article>
.
Note that outer and inner locators must belong to the same frame. Inner locator must not contain [FrameLocator]s.
- %%-locator-option-has-text-%%
- %%-locator-option-has-%%
animations
<[ScreenshotAnimations]<"disabled"|"allow">>
When set to "disabled"
, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:
- finite animations are fast-forwarded to completion, so they'll fire
transitionend
event. - infinite animations are canceled to initial state, and then played over after the screenshot.
Defaults to "allow"
that leaves animations untouched.
animations
<[ScreenshotAnimations]<"disabled"|"allow">>
When set to "disabled"
, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:
- finite animations are fast-forwarded to completion, so they'll fire
transitionend
event. - infinite animations are canceled to initial state, and then played over after the screenshot.
Defaults to "disabled"
that disables animations.
omitBackground
<[boolean]>
Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg
images.
Defaults to false
.
quality
<[int]>
The quality of the image, between 0-100. Not applicable to png
images.
path
<[path]>
The file path to save the image to. The screenshot type will be inferred from file extension. If [option: path
] is a
relative path, then it is resolved relative to the current working directory. If no path is provided, the image won't be
saved to the disk.
type
<[ScreenshotType]<"png"|"jpeg">>
Specify screenshot type, defaults to png
.
mask
<[Array]<[Locator]>>
Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with
a pink box #FF00FF
that completely covers its bounding box.
fullPage
<[boolean]>
When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to
false
.
clip
<[Object]>x
<[float]> x-coordinate of top-left corner of clip areay
<[float]> y-coordinate of top-left corner of clip areawidth
<[float]> width of clipping areaheight
<[float]> height of clipping area
An object which specifies clipping of the resulting image. Should have the following fields:
scale
<[ScreenshotScale]<"css"|"device">>
When set to "css"
, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will keep screenshots small. Using "device"
option will produce a single pixel per each device pixel, so screenshots of high-dpi devices will be twice as large or even larger.
Defaults to "device"
.
scale
<[ScreenshotScale]<"css"|"device">>
When set to "css"
, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will keep screenshots small. Using "device"
option will produce a single pixel per each device pixel, so screenshots of high-dpi devices will be twice as large or even larger.
Defaults to "css"
.
caret
<[ScreenshotCaret]<"hide"|"initial">>
When set to "hide"
, screenshot will hide text caret. When set to "initial"
, text caret behavior will not be changed. Defaults to "hide"
.
- %%-screenshot-option-animations-%%
- %%-screenshot-option-omit-background-%%
- %%-screenshot-option-quality-%%
- %%-screenshot-option-path-%%
- %%-screenshot-option-scale-%%
- %%-screenshot-option-caret-%%
- %%-screenshot-option-type-%%
- %%-screenshot-option-mask-%%
- %%-input-timeout-%%
- since: v1.27
testId
<[string]|[RegExp]>
Id to locate the element by.
- since: v1.27
text
<[string]|[RegExp]>
Text to locate the element for.
- since: v1.27
exact
<[boolean]>
Whether 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.
- since: v1.27
role
<[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.
- since: v1.27
checked
<[boolean]>
An attribute that is usually set by aria-checked
or native <input type=checkbox>
controls.
Learn more about aria-checked
.
- since: v1.27
disabled
<[boolean]>
An 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
.
:::
- since: v1.27
expanded
<[boolean]>
An attribute that is usually set by aria-expanded
.
Learn more about aria-expanded
.
locator-get-by-role-option-includeHidden
- since: v1.27
includeHidden
<[boolean]>
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
.
- since: v1.27
level
<[int]>
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
.
- since: v1.27
name
<[string]|[RegExp]>
Option to match the accessible name. By default, matching is case-insensitive and searches for a substring, use [option: exact
] to control this behavior.
Learn more about accessible name.
- since: v1.28
exact
<[boolean]>
Whether [option: name
] is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when [option: name
] is a regular expression. Note that exact match still trims whitespace.
- since: v1.27
pressed
<[boolean]>
An attribute that is usually set by aria-pressed
.
Learn more about aria-pressed
.
- since: v1.27
selected
An attribute that is usually set by aria-selected
.
Learn more about aria-selected
.
- %%-locator-get-by-role-option-checked-%%
- %%-locator-get-by-role-option-disabled-%%
- %%-locator-get-by-role-option-expanded-%%
- %%-locator-get-by-role-option-includeHidden-%%
- %%-locator-get-by-role-option-level-%%
- %%-locator-get-by-role-option-name-%%
- %%-locator-get-by-role-option-pressed-%%
- %%-locator-get-by-role-option-selected-%%
The method finds an element matching the specified selector in the locator's subtree. It also accepts filter options, similar to [method: Locator.filter
] method.
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.
Locate element by the test id. By default, the data-testid
attribute is used as a test id. Use [method: Selectors.setTestIdAttribute
] to configure a different test id attribute if necessary.
// Set custom test id attribute from @playwright/test config:
use: {
testIdAttribute: 'data-pw'
}
Allows locating elements that contain given text. 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)
# Matches <span>
page.get_by_text("world")
# Matches first <div>
page.get_by_text("Hello world")
# Matches second <div>
page.get_by_text("Hello", exact=True)
# Matches both <div>s
page.get_by_text(re.compile("Hello"))
# Matches second <div>
page.get_by_text(re.compile("^hello$", re.IGNORECASE))
# Matches <span>
page.get_by_text("world")
# Matches first <div>
page.get_by_text("Hello world")
# Matches second <div>
page.get_by_text("Hello", exact=True)
# Matches both <div>s
page.get_by_text(re.compile("Hello"))
# Matches second <div>
page.get_by_text(re.compile("^hello$", re.IGNORECASE))
// 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))
// Matches <span>
page.GetByText("world")
// Matches first <div>
page.GetByText("Hello world")
// Matches second <div>
page.GetByText("Hello", new() { Exact: true })
// Matches both <div>s
page.GetByText(new Regex("Hello"))
// Matches second <div>
page.GetByText(new Regex("^hello$", RegexOptions.IgnoreCase))
See also [method: Locator.filter
] that allows to match by another criteria, like an accessible role, and then filter by the text content.
:::note 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. :::
:::note
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">
.
:::
Allows locating elements by their alt text. For example, this method will find the image by alt text "Castle":
<img alt='Castle'>
Allows locating input elements by the text of the associated label. For example, this method will find the input by label text "Password" in the following DOM:
<label for="password-input">Password:</label>
<input id="password-input">
Allows locating input elements by the placeholder text. For example, this method will find the input by placeholder "Country":
<input placeholder="Country">
Allows locating elements by their ARIA role, ARIA attributes and accessible name. Note that role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
Note that 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.
Allows locating elements by their title. For example, this method will find the button by its title "Place the order":
<button title='Place the order'>Order Now</button>
type
?<[string]>
- langs: js
This option configures a template controlling location of snapshots generated by [method: PageAssertions.toHaveScreenshot#1
] and [method: SnapshotAssertions.toMatchSnapshot#1
].
// playwright.config.ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
testDir: './tests',
snapshotPathTemplate: '{testDir}/__screenshots__/{testFilePath}/{arg}{ext}',
};
export default config;
// playwright.config.js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
testDir: './tests',
snapshotPathTemplate: '{testDir}/__screenshots__/{testFilePath}/{arg}{ext}',
};
module.exports = config;
The value might include some "tokens" that will be replaced with actual values during test execution.
Consider the following file structure:
playwright.config.ts
tests/
└── page/
└── page-click.spec.ts
And the following page-click.spec.ts
that uses toHaveScreenshot()
call:
// page-click.spec.ts
import { test, expect } from '@playwright/test';
test.describe('suite', () => {
test('test should work', async ({ page }) => {
await expect(page).toHaveScreenshot(['foo', 'bar', 'baz.png']);
});
});
// page-click.spec.js
const { test, expect } = require('@playwright/test');
test.describe('suite', () => {
test('test should work', async ({ page }) => {
await expect(page).toHaveScreenshot(['foo', 'bar', 'baz.png']);
});
});
The list of supported tokens:
{testDir}
- Project's [property: TestConfig.testDir
].- Value:
/home/playwright/tests
(absolute path is sincetestDir
is resolved relative to directory with config)
- Value:
{snapshotDir}
- Project's [property: TestConfig.snapshotDir
].- Value:
/home/playwright/tests
(sincesnapshotDir
is not provided in config, it defaults totestDir
)
- Value:
{platform}
- The value ofprocess.platform
.{projectName}
- Project's file-system-sanitized name, if any.- Value:
''
(empty string).
- Value:
{testFileDir}
- Directories in relative path fromtestDir
to test file.- Value:
page
- Value:
{testFileName}
- Test file name with extension.- Value:
page-click.spec.ts
- Value:
{testFilePath}
- Relative path fromtestDir
to test file- Value:
page/page-click.spec.ts
- Value:
{testName}
- File-system-sanitized test title, including parent describes but excluding file name.- Value:
suite-test-should-work
- Value:
{arg}
- Relative snapshot path without extension. These come from the arguments passed to thetoHaveScreenshot()
andtoMatchSnapshot()
calls; if called without arguments, this will be an auto-generated snapshot name.- Value:
foo/bar/baz
- Value:
{ext}
- snapshot extension (with dots)- Value:
.png
- Value:
Each token can be preceded with a single character that will be used only if this token has non-empty value.
Consider the following config:
// playwright.config.ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
snapshotPathTemplate: '__screenshots__{/projectName}/{testFilePath}/{arg}{ext}',
testMatch: 'example.spec.ts',
projects: [
{ use: { browserName: 'firefox' } },
{ name: 'chromium', use: { browserName: 'chromium' } },
],
};
export default config;
// playwright.config.js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
snapshotPathTemplate: '__screenshots__{/projectName}/{testFilePath}/{arg}{ext}',
testMatch: 'example.spec.ts',
projects: [
{ use: { browserName: 'firefox' } },
{ name: 'chromium', use: { browserName: 'chromium' } },
],
};
module.exports = config;
In this config:
- First project does not have a name, so its snapshots will be stored in
<configDir>/__screenshots__/example.spec.ts/...
. - Second project does have a name, so its snapshots will be stored in
<configDir>/__screenshots__/chromium/example.spec.ts/..
. - Since
snapshotPathTemplate
resolves to relative path, it will be resolved relative toconfigDir
. - Forward slashes
"/"
can be used as path separators on any platform.