package playwright
// Exposes API that can be used for the Web API testing. This class is used for creating [APIRequestContext] instance
// which in turn can be used for sending web requests. An instance of this class can be obtained via
// [Playwright.Request]. For more information see [APIRequestContext].
type APIRequest interface {
// Creates new instances of [APIRequestContext].
NewContext(options ...APIRequestNewContextOptions) (APIRequestContext, error)
}
// This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services,
// prepare environment or the service to your e2e test.
// Each Playwright browser context has associated with it [APIRequestContext] instance which shares cookie storage
// with the browser context and can be accessed via [BrowserContext.Request] or [Page.Request]. It is also possible to
// create a new APIRequestContext instance manually by calling [APIRequest.NewContext].
// **Cookie management**
// [APIRequestContext] returned by [BrowserContext.Request] and [Page.Request] shares cookie storage with the
// corresponding [BrowserContext]. Each API request will have `Cookie` header populated with the values from the
// browser context. If the API response contains `Set-Cookie` header it will automatically update [BrowserContext]
// cookies and requests made from the page will pick them up. This means that if you log in using this API, your e2e
// test will be logged in and vice versa.
// If you want API requests to not interfere with the browser cookies you should create a new [APIRequestContext] by
// calling [APIRequest.NewContext]. Such `APIRequestContext` object will have its own isolated cookie storage.
type APIRequestContext interface {
// Sends HTTP(S) [DELETE] request and returns its
// response. The method will populate request cookies from the context and update context cookies from the response.
// The method will automatically follow redirects.
//
// url: Target URL.
//
// [DELETE]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE
Delete(url string, options ...APIRequestContextDeleteOptions) (APIResponse, error)
// All responses returned by [APIRequestContext.Get] and similar methods are stored in the memory, so that you can
// later call [APIResponse.Body].This method discards all its resources, calling any method on disposed
// [APIRequestContext] will throw an exception.
Dispose(options ...APIRequestContextDisposeOptions) error
// Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and
// update context cookies from the response. The method will automatically follow redirects.
//
// urlOrRequest: Target URL or Request to get all parameters from.
Fetch(urlOrRequest interface{}, options ...APIRequestContextFetchOptions) (APIResponse, error)
// Sends HTTP(S) [GET] request and returns its
// response. The method will populate request cookies from the context and update context cookies from the response.
// The method will automatically follow redirects.
//
// url: Target URL.
//
// [GET]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET
Get(url string, options ...APIRequestContextGetOptions) (APIResponse, error)
// Sends HTTP(S) [HEAD] request and returns its
// response. The method will populate request cookies from the context and update context cookies from the response.
// The method will automatically follow redirects.
//
// url: Target URL.
//
// [HEAD]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
Head(url string, options ...APIRequestContextHeadOptions) (APIResponse, error)
// Sends HTTP(S) [PATCH] request and returns its
// response. The method will populate request cookies from the context and update context cookies from the response.
// The method will automatically follow redirects.
//
// url: Target URL.
//
// [PATCH]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH
Patch(url string, options ...APIRequestContextPatchOptions) (APIResponse, error)
// Sends HTTP(S) [POST] request and returns its
// response. The method will populate request cookies from the context and update context cookies from the response.
// The method will automatically follow redirects.
//
// url: Target URL.
//
// [POST]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Post(url string, options ...APIRequestContextPostOptions) (APIResponse, error)
// Sends HTTP(S) [PUT] request and returns its
// response. The method will populate request cookies from the context and update context cookies from the response.
// The method will automatically follow redirects.
//
// url: Target URL.
//
// [PUT]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT
Put(url string, options ...APIRequestContextPutOptions) (APIResponse, error)
// Returns storage state for this request context, contains current cookies and local storage snapshot if it was
// passed to the constructor.
StorageState(path ...string) (*StorageState, error)
}
// [APIResponse] class represents responses returned by [APIRequestContext.Get] and similar methods.
type APIResponse interface {
// Returns the buffer with response body.
Body() ([]byte, error)
// Disposes the body of this response. If not called then the body will stay in memory until the context closes.
Dispose() error
// An object with all the response HTTP headers associated with this response.
Headers() map[string]string
// An array with all the response HTTP headers associated with this response. Header names are not lower-cased.
// Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.
HeadersArray() []NameValue
// Returns the JSON representation of response body.
// This method will throw if the response body is not parsable via `JSON.parse`.
JSON(v interface{}) error
// Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
Ok() bool
// Contains the status code of the response (e.g., 200 for a success).
Status() int
// Contains the status text of the response (e.g. usually an "OK" for a success).
StatusText() string
// Returns the text representation of response body.
Text() (string, error)
// Contains the URL of the response.
URL() string
}
// The [APIResponseAssertions] class provides assertion methods that can be used to make assertions about the
// [APIResponse] in the tests.
type APIResponseAssertions interface {
// Makes the assertion check for the opposite condition. For example, this code tests that the response status is not
// successful:
Not() APIResponseAssertions
// Ensures the response status code is within `200..299` range.
ToBeOK() error
}
// A Browser is created via [BrowserType.Launch]. An example of using a [Browser] to create a [Page]:
type Browser interface {
EventEmitter
// Emitted when Browser gets disconnected from the browser application. This might happen because of one of the
// following:
// - Browser application is closed or crashed.
// - The [Browser.Close] method was called.
OnDisconnected(fn func(Browser))
// Get the browser type (chromium, firefox or webkit) that the browser belongs to.
BrowserType() BrowserType
// In case this browser is obtained using [BrowserType.Launch], closes the browser and all of its pages (if any were
// opened).
// In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from
// the browser server.
// **NOTE** This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close
// events, call [BrowserContext.Close] on any [BrowserContext] instances you explicitly created earlier using
// [Browser.NewContext] **before** calling [Browser.Close].
// The [Browser] object itself is considered to be disposed and cannot be used anymore.
Close(options ...BrowserCloseOptions) error
// Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
Contexts() []BrowserContext
// Indicates that the browser is connected.
IsConnected() bool
// **NOTE** CDP Sessions are only supported on Chromium-based browsers.
// Returns the newly created browser session.
NewBrowserCDPSession() (CDPSession, error)
// Creates a new browser context. It won't share cookies/cache with other browser contexts.
// **NOTE** If directly using this method to create [BrowserContext]s, it is best practice to explicitly close the
// returned context via [BrowserContext.Close] when your code is done with the [BrowserContext], and before calling
// [Browser.Close]. This will ensure the `context` is closed gracefully and any artifacts—like HARs and videos—are
// fully flushed and saved.
NewContext(options ...BrowserNewContextOptions) (BrowserContext, error)
// Creates a new page in a new browser context. Closing this page will close the context as well.
// This is a convenience API that should only be used for the single-page scenarios and short snippets. Production
// code and testing frameworks should explicitly create [Browser.NewContext] followed by the [BrowserContext.NewPage]
// to control their exact life times.
NewPage(options ...BrowserNewPageOptions) (Page, error)
// **NOTE** This API controls
// [Chromium Tracing] which is a low-level
// chromium-specific debugging tool. API to control [Playwright Tracing] could be found
// [here].
// You can use [Browser.StartTracing] and [Browser.StopTracing] to create a trace file that can be opened in Chrome
// DevTools performance panel.
//
// [Chromium Tracing]: https://www.chromium.org/developers/how-tos/trace-event-profiling-tool
// [Playwright Tracing]: ../trace-viewer
// [here]: ./class-tracing
StartTracing(options ...BrowserStartTracingOptions) error
// **NOTE** This API controls
// [Chromium Tracing] which is a low-level
// chromium-specific debugging tool. API to control [Playwright Tracing] could be found
// [here].
// Returns the buffer with trace data.
//
// [Chromium Tracing]: https://www.chromium.org/developers/how-tos/trace-event-profiling-tool
// [Playwright Tracing]: ../trace-viewer
// [here]: ./class-tracing
StopTracing() ([]byte, error)
// Returns the browser version.
Version() string
}
// BrowserContexts provide a way to operate multiple independent browser sessions.
// If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser
// context.
// Playwright allows creating isolated non-persistent browser contexts with [Browser.NewContext] method.
// Non-persistent browser contexts don't write any browsing data to disk.
type BrowserContext interface {
EventEmitter
// **NOTE** Only works with Chromium browser's persistent context.
// Emitted when new background page is created in the context.
OnBackgroundPage(fn func(Page))
// Playwright has ability to mock clock and passage of time.
Clock() Clock
// Emitted when Browser context gets closed. This might happen because of one of the following:
// - Browser context is closed.
// - Browser application is closed or crashed.
// - The [Browser.Close] method was called.
OnClose(fn func(BrowserContext))
// Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.
// The arguments passed into `console.log` and the page are available on the [ConsoleMessage] event handler argument.
OnConsole(fn func(ConsoleMessage))
// Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
// either [Dialog.Accept] or [Dialog.Dismiss] the dialog - otherwise the page will
// [freeze] waiting for the dialog,
// and actions like click will never finish.
//
// [freeze]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking
OnDialog(fn func(Dialog))
// The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
// will also fire for popup pages. See also [Page.OnPopup] to receive events about popups relevant to a specific page.
// The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
// popup with `window.open('http://example.com')`, this event will fire when the network request to
// "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen
// to this network request, use [BrowserContext.Route] and [BrowserContext.OnRequest] respectively instead of similar
// methods on the [Page].
// **NOTE** Use [Page.WaitForLoadState] to wait until the page gets to a particular state (you should not need it in
// most cases).
OnPage(fn func(Page))
// Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
// page, use [Page.OnPageError] instead.
OnWebError(fn func(WebError))
// Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
// only listen for requests from a particular page, use [Page.OnRequest].
// In order to intercept and mutate requests, see [BrowserContext.Route] or [Page.Route].
OnRequest(fn func(Request))
// Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
// use [Page.OnRequestFailed].
// **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
// will complete with [BrowserContext.OnRequestFinished] event and not with [BrowserContext.OnRequestFailed].
OnRequestFailed(fn func(Request))
// Emitted when a request finishes successfully after downloading the response body. For a successful response, the
// sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
// particular page, use [Page.OnRequestFinished].
OnRequestFinished(fn func(Request))
// Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
// events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
// [Page.OnResponse].
OnResponse(fn func(Response))
// Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies
// can be obtained via [BrowserContext.Cookies].
AddCookies(cookies []OptionalCookie) error
// Adds a script which would be evaluated in one of the following scenarios:
// - Whenever a page is created in the browser context or is navigated.
// - Whenever a child frame is attached or navigated in any page in the browser context. 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`.
//
// script: Script to be evaluated in all pages in the browser context.
AddInitScript(script Script) error
// **NOTE** Background pages are only supported on Chromium-based browsers.
// All existing background pages in the context.
BackgroundPages() []Page
// Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
Browser() Browser
// Removes cookies from context. Accepts optional filter.
ClearCookies(options ...BrowserContextClearCookiesOptions) error
// Clears all permission overrides for the browser context.
ClearPermissions() error
// Closes the browser context. All the pages that belong to the browser context will be closed.
// **NOTE** The default browser context cannot be closed.
Close(options ...BrowserContextCloseOptions) error
// If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those
// URLs are returned.
Cookies(urls ...string) ([]Cookie, error)
// The method adds a function called “[object Object]” on the `window` object of every frame in every page in the
// context. When called, the function executes “[object Object]” and returns a [Promise] which resolves to the return
// value of “[object Object]”. If the “[object Object]” returns a [Promise], it will be awaited.
// The first argument of the “[object Object]” function contains information about the caller: `{ browserContext:
// BrowserContext, page: Page, frame: Frame }`.
// See [Page.ExposeBinding] for page-only version.
//
// 1. name: Name of the function on the window object.
// 2. binding: Callback function that will be called in the Playwright's context.
ExposeBinding(name string, binding BindingCallFunction, handle ...bool) error
// The method adds a function called “[object Object]” on the `window` object of every frame in every page in the
// context. When called, the function executes “[object Object]” and returns a [Promise] which resolves to the return
// value of “[object Object]”.
// If the “[object Object]” returns a [Promise], it will be awaited.
// See [Page.ExposeFunction] for page-only version.
//
// 1. name: Name of the function on the window object.
// 2. binding: Callback function that will be called in the Playwright's context.
ExposeFunction(name string, binding ExposedFunction) error
// Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
// specified.
//
// permissions: A list of permissions to grant.
//
// **NOTE** Supported permissions differ between browsers, and even between different versions of the same browser.
// Any permission may stop working after an update.
//
// Here are some permissions that may be supported by some browsers:
// - `'accelerometer'`
// - `'ambient-light-sensor'`
// - `'background-sync'`
// - `'camera'`
// - `'clipboard-read'`
// - `'clipboard-write'`
// - `'geolocation'`
// - `'gyroscope'`
// - `'magnetometer'`
// - `'microphone'`
// - `'midi-sysex'` (system-exclusive midi)
// - `'midi'`
// - `'notifications'`
// - `'payment-handler'`
// - `'storage-access'`
GrantPermissions(permissions []string, options ...BrowserContextGrantPermissionsOptions) error
// **NOTE** CDP sessions are only supported on Chromium-based browsers.
// Returns the newly created session.
//
// page: Target to create new session for. For backwards-compatibility, this parameter is named `page`, but it can be a
// `Page` or `Frame` type.
NewCDPSession(page interface{}) (CDPSession, error)
// Creates a new page in the browser context.
NewPage() (Page, error)
// Returns all open pages in the context.
Pages() []Page
// API testing helper associated with this context. Requests made with this API will use context cookies.
Request() APIRequestContext
// Routing provides the capability to modify network requests that are made by any page in the browser context. Once
// route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
// **NOTE** [BrowserContext.Route] will not intercept requests intercepted by Service Worker. See
// [this] issue. We recommend disabling Service Workers when
// using request interception by setting “[object Object]” to `block`.
//
// 1. url: A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a “[object Object]” via the
// context options was provided and the passed URL is a path, it gets merged via the
// [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
// 2. handler: handler function to route the request.
//
// [this]: https://github.com/microsoft/playwright/issues/1090
Route(url interface{}, handler routeHandler, times ...int) error
// If specified the network requests that are made in the context will be served from the HAR file. Read more about
// [Replaying from HAR].
// Playwright will not serve requests intercepted by Service Worker from the HAR file. See
// [this] issue. We recommend disabling Service Workers when
// using request interception by setting “[object Object]” to `block`.
//
// har: Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
// relative path, then it is resolved relative to the current working directory.
//
// [Replaying from HAR]: https://playwright.dev/docs/mock#replaying-from-har
// [this]: https://github.com/microsoft/playwright/issues/1090
RouteFromHAR(har string, options ...BrowserContextRouteFromHAROptions) error
// This method allows to modify websocket connections that are made by any page in the browser context.
// Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this
// method before creating any pages.
//
// 1. url: Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
// “[object Object]” context option.
// 2. handler: Handler function to route the WebSocket.
RouteWebSocket(url interface{}, handler func(WebSocketRoute)) error
// **NOTE** Service workers are only supported on Chromium-based browsers.
// All existing service workers in the context.
ServiceWorkers() []Worker
// This setting will change the default maximum navigation time for the following methods and related shortcuts:
// - [Page.GoBack]
// - [Page.GoForward]
// - [Page.Goto]
// - [Page.Reload]
// - [Page.SetContent]
// - [Page.ExpectNavigation]
// **NOTE** [Page.SetDefaultNavigationTimeout] and [Page.SetDefaultTimeout] take priority over
// [BrowserContext.SetDefaultNavigationTimeout].
//
// timeout: Maximum navigation time in milliseconds
SetDefaultNavigationTimeout(timeout float64)
// This setting will change the default maximum time for all the methods accepting “[object Object]” option.
// **NOTE** [Page.SetDefaultNavigationTimeout], [Page.SetDefaultTimeout] and
// [BrowserContext.SetDefaultNavigationTimeout] take priority over [BrowserContext.SetDefaultTimeout].
//
// timeout: Maximum time in milliseconds. Pass `0` to disable timeout.
SetDefaultTimeout(timeout float64)
// The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are
// merged with page-specific extra HTTP headers set with [Page.SetExtraHTTPHeaders]. If page overrides a particular
// header, page-specific header value will be used instead of the browser context header value.
// **NOTE** [BrowserContext.SetExtraHTTPHeaders] does not guarantee the order of headers in the outgoing requests.
//
// headers: An object containing additional HTTP headers to be sent with every request. All header values must be strings.
SetExtraHTTPHeaders(headers map[string]string) error
// Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
SetGeolocation(geolocation *Geolocation) error
//
// offline: Whether to emulate network being offline for the browser context.
SetOffline(offline bool) error
// Returns storage state for this browser context, contains current cookies and local storage snapshot.
StorageState(path ...string) (*StorageState, error)
Tracing() Tracing
// Removes all routes created with [BrowserContext.Route] and [BrowserContext.RouteFromHAR].
UnrouteAll(options ...BrowserContextUnrouteAllOptions) error
// Removes a route created with [BrowserContext.Route]. When “[object Object]” is not specified, removes all routes
// for the “[object Object]”.
//
// 1. url: A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with [BrowserContext.Route].
// 2. handler: Optional handler function used to register a routing with [BrowserContext.Route].
Unroute(url interface{}, handler ...routeHandler) error
// Performs action and waits for a [ConsoleMessage] to be logged by in the pages in the context. If predicate is
// provided, it passes [ConsoleMessage] value into the `predicate` function and waits for `predicate(message)` to
// return a truthy value. Will throw an error if the page is closed before the [BrowserContext.OnConsole] event is
// fired.
ExpectConsoleMessage(cb func() error, options ...BrowserContextExpectConsoleMessageOptions) (ConsoleMessage, error)
// Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
// value. Will throw an error if the context closes before the event is fired. Returns the event data value.
//
// event: Event name, same one would pass into `browserContext.on(event)`.
ExpectEvent(event string, cb func() error, options ...BrowserContextExpectEventOptions) (interface{}, error)
// Performs action and waits for a new [Page] to be created in the context. If predicate is provided, it passes [Page]
// value into the `predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error
// if the context closes before new [Page] is created.
ExpectPage(cb func() error, options ...BrowserContextExpectPageOptions) (Page, error)
// **NOTE** In most cases, you should use [BrowserContext.ExpectEvent].
// Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function
// and waits for `predicate(event)` to return a truthy value. Will throw an error if the browser context is closed
// before the `event` is fired.
//
// event: Event name, same one typically passed into `*.on(event)`.
WaitForEvent(event string, options ...BrowserContextWaitForEventOptions) (interface{}, error)
}
// BrowserType provides methods to launch a specific browser instance or connect to an existing one. The following is
// a typical example of using Playwright to drive automation:
type BrowserType interface {
// This method attaches Playwright to an existing browser instance created via `BrowserType.launchServer` in Node.js.
// **NOTE** The major and minor version of the Playwright instance that connects needs to match the version of
// Playwright that launches the browser (1.2.3 → is compatible with 1.2.x).
//
// wsEndpoint: A Playwright browser websocket endpoint to connect to. You obtain this endpoint via `BrowserServer.wsEndpoint`.
Connect(wsEndpoint string, options ...BrowserTypeConnectOptions) (Browser, error)
// This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
// The default browser context is accessible via [Browser.Contexts].
// **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
// **NOTE** This connection is significantly lower fidelity than the Playwright protocol connection via
// [BrowserType.Connect]. If you are experiencing issues or attempting to use advanced functionality, you probably
// want to use [BrowserType.Connect].
//
// endpointURL: A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
// `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
ConnectOverCDP(endpointURL string, options ...BrowserTypeConnectOverCDPOptions) (Browser, error)
// A path where Playwright expects to find a bundled browser executable.
ExecutablePath() string
// Returns the browser instance.
//
// [Chrome Canary]: https://www.google.com/chrome/browser/canary.html
// [Dev Channel]: https://www.chromium.org/getting-involved/dev-channel
// [this article]: https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/
// [This article]: https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md
Launch(options ...BrowserTypeLaunchOptions) (Browser, error)
// Returns the persistent browser context instance.
// Launches browser that uses persistent storage located at “[object Object]” and returns the only context. Closing
// this context will automatically close the browser.
//
// userDataDir: Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for
// [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
// [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile). Note that Chromium's
// user data directory is the **parent** directory of the "Profile Path" seen at `chrome://version`. Pass an empty
// string to use a temporary directory instead.
LaunchPersistentContext(userDataDir string, options ...BrowserTypeLaunchPersistentContextOptions) (BrowserContext, error)
// Returns browser name. For example: `chromium`, `webkit` or `firefox`.
Name() string
}
// The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
// - protocol methods can be called with `session.send` method.
// - protocol events can be subscribed to with `session.on` method.
//
// Useful links:
// - Documentation on DevTools Protocol can be found here:
// [DevTools Protocol Viewer].
// - Getting Started with DevTools Protocol:
// https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md
//
// [DevTools Protocol Viewer]: https://chromedevtools.github.io/devtools-protocol/
type CDPSession interface {
EventEmitter
// Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be
// used to send messages.
Detach() error
//
// 1. method: Protocol method name.
// 2. params: Optional method parameters.
Send(method string, params map[string]interface{}) (interface{}, error)
}
// Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn
// more about [clock emulation].
// Note that clock is installed for the entire [BrowserContext], so the time in all the pages and iframes is
// controlled by the same clock.
//
// [clock emulation]: https://playwright.dev/docs/clock
type Clock interface {
// Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user
// closing the laptop lid for a while and reopening it later, after given time.
//
// ticks: Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
// "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
FastForward(ticks interface{}) error
// Install fake implementations for the following time-related functions:
// - `Date`
// - `setTimeout`
// - `clearTimeout`
// - `setInterval`
// - `clearInterval`
// - `requestAnimationFrame`
// - `cancelAnimationFrame`
// - `requestIdleCallback`
// - `cancelIdleCallback`
// - `performance`
// Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,
// and control the behavior of time-dependent functions. See [Clock.RunFor] and [Clock.FastForward] for more
// information.
Install(options ...ClockInstallOptions) error
// Advance the clock, firing all the time-related callbacks.
//
// ticks: Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are
// "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.
RunFor(ticks interface{}) error
// Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired
// unless [Clock.RunFor], [Clock.FastForward], [Clock.PauseAt] or [Clock.Resume] is called.
// Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it
// at the specified time and pausing.
//
// time: Time to pause at.
PauseAt(time interface{}) error
// Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.
Resume() error
// Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.
// Use this method for simple scenarios where you only need to test with a predefined time. For more advanced
// scenarios, use [Clock.Install] instead. Read docs on [clock emulation] to learn more.
//
// time: Time to be set.
//
// [clock emulation]: https://playwright.dev/docs/clock
SetFixedTime(time interface{}) error
// Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for
// example switching from summer to winter time, or changing time zones.
//
// time: Time to be set.
SetSystemTime(time interface{}) error
}
// [ConsoleMessage] objects are dispatched by page via the [Page.OnConsole] event. For each console message logged in
// the page there will be corresponding event in the Playwright context.
type ConsoleMessage interface {
// List of arguments passed to a `console` function call. See also [Page.OnConsole].
Args() []JSHandle
Location() *ConsoleMessageLocation
// The page that produced this console message, if any.
Page() Page
// The text of the console message.
Text() string
// The text of the console message.
String() string
// One of the following values: `log`, `debug`, `info`, `error`, `warning`, `dir`, `dirxml`, `table`,
// `trace`, `clear`, `startGroup`, `startGroupCollapsed`, `endGroup`, `assert`, `profile`,
// `profileEnd`, `count`, `timeEnd`.
Type() string
}
// [Dialog] objects are dispatched by page via the [Page.OnDialog] event.
// An example of using `Dialog` class:
// **NOTE** Dialogs are dismissed automatically, unless there is a [Page.OnDialog] listener. When listener is present,
// it **must** either [Dialog.Accept] or [Dialog.Dismiss] the dialog - otherwise the page will
// [freeze] waiting for the dialog,
// and actions like click will never finish.
//
// [freeze]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking
type Dialog interface {
// Returns when the dialog has been accepted.
Accept(promptText ...string) error
// If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
DefaultValue() string
// Returns when the dialog has been dismissed.
Dismiss() error
// A message displayed in the dialog.
Message() string
// The page that initiated this dialog, if available.
Page() Page
// Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
Type() string
}
// [Download] objects are dispatched by page via the [Page.OnDownload] event.
// All the downloaded files belonging to the browser context are deleted when the browser context is closed.
// Download event is emitted once the download starts. Download path becomes available once download completes.
type Download interface {
// Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,
// `download.failure()` would resolve to `canceled`.
Cancel() error
// Deletes the downloaded file. Will wait for the download to finish if necessary.
Delete() error
// Returns download error if any. Will wait for the download to finish if necessary.
Failure() error
// Get the page that the download belongs to.
Page() Page
// Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method
// will wait for the download to finish if necessary. The method throws when connected remotely.
// Note that the download's file name is a random GUID, use [Download.SuggestedFilename] to get suggested file name.
Path() (string, error)
// Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.
// Will wait for the download to finish if necessary.
//
// path: Path where the download should be copied.
SaveAs(path string) error
// Returns suggested filename for this download. It is typically computed by the browser from the
// [`Content-Disposition`] response
// header or the `download` attribute. See the spec on [whatwg].
// Different browsers can use different logic for computing it.
//
// [`Content-Disposition`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
// [whatwg]: https://html.spec.whatwg.org/#downloading-resources
SuggestedFilename() string
// Returns downloaded url.
URL() string
String() string
}
// ElementHandle represents an in-page DOM element. ElementHandles can be created with the [Page.QuerySelector]
//
// method.
// **NOTE** The use of ElementHandle is discouraged, use [Locator] objects and web-first assertions instead.
// ElementHandle prevents DOM element from garbage collection unless the handle is disposed with [JSHandle.Dispose].
// ElementHandles are auto-disposed when their origin frame gets navigated.
// ElementHandle instances can be used as an argument in [Page.EvalOnSelector] and [Page.Evaluate] methods.
// The difference between the [Locator] and ElementHandle is that the ElementHandle points to a particular element,
// while [Locator] captures the logic of how to retrieve an element.
// In the example below, handle points to a particular DOM element on page. If that element changes text or is used by
// React to render an entirely different component, handle is still pointing to that very DOM element. This can lead
// to unexpected behaviors.
// With the locator, every time the `element` is used, up-to-date DOM element is located in the page using the
// selector. So in the snippet below, underlying DOM element is going to be located twice.
type ElementHandle interface {
JSHandle
// This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
// calculated relative to the main frame viewport - which is usually the same as the browser window.
// Scrolling affects the returned bounding box, similarly to
// [Element.GetBoundingClientRect].
// That means `x` and/or `y` may be negative.
// Elements from child frames return the bounding box relative to the main frame, unlike the
// [Element.GetBoundingClientRect].
// Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
// following snippet should click the center of the element.
//
// [Element.GetBoundingClientRect]: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
// [Element.GetBoundingClientRect]: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
BoundingBox() (*Rect, error)
// This method checks the element by performing the following steps:
// 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
// checked, this method returns immediately.
// 2. Wait for [actionability] checks on the element, unless “[object Object]” option is set.
// 3. Scroll the element into view if needed.
// 4. Use [Page.Mouse] to click in the center of the element.
// 5. Ensure that the element is now checked. If not, this method throws.
// If the element is detached from the DOM at any moment during the action, this method throws.
// When all steps combined have not finished during the specified “[object Object]”, this method throws a
// [TimeoutError]. Passing zero timeout disables this.
//
// Deprecated: Use locator-based [Locator.Check] instead. Read more about [locators].
//
// [actionability]: https://playwright.dev/docs/actionability
// [locators]: https://playwright.dev/docs/locators
Check(options ...ElementHandleCheckOptions) error
// This method clicks the element by performing the following steps:
// 1. Wait for [actionability] checks on the element, unless “[object Object]” option is set.
// 2. Scroll the element into view if needed.
// 3. Use [Page.Mouse] to click in the center of the element, or the specified “[object Object]”.
// 4. Wait for initiated navigations to either succeed or fail, unless “[object Object]” option is set.
// If the element is detached from the DOM at any moment during the action, this method throws.
// When all steps combined have not finished during the specified “[object Object]”, this method throws a
// [TimeoutError]. Passing zero timeout disables this.
//
// Deprecated: Use locator-based [Locator.Click] instead. Read more about [locators].
//
// [actionability]: https://playwright.dev/docs/actionability
// [locators]: https://playwright.dev/docs/locators
Click(options ...ElementHandleClickOptions) error
// Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
ContentFrame() (Frame, error)
// This method double clicks the element by performing the following steps:
// 1. Wait for [actionability] checks on the element, unless “[object Object]” option is set.
// 2. Scroll the element into view if needed.
// 3. Use [Page.Mouse] to double click in the center of the element, or the specified “[object Object]”.
// If the element is detached from the DOM at any moment during the action, this method throws.
// When all steps combined have not finished during the specified “[object Object]”, this method throws a
// [TimeoutError]. Passing zero timeout disables this.
// **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
//
// Deprecated: Use locator-based [Locator.Dblclick] instead. Read more about [locators].
//
// [actionability]: https://playwright.dev/docs/actionability
// [locators]: https://playwright.dev/docs/locators
Dblclick(options ...ElementHandleDblclickOptions) error
// 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()].
//
// Deprecated: Use locator-based [Locator.DispatchEvent] instead. Read more about [locators].
//
// 1. typ: DOM event type: `"click"`, `"dragstart"`, etc.
// 2. eventInit: Optional event-specific initialization properties.
//
// [element.Click()]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
// [DeviceMotionEvent]: https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent
// [DeviceOrientationEvent]: https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent
// [DragEvent]: https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent
// [Event]: https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
// [FocusEvent]: https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent
// [KeyboardEvent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
// [MouseEvent]: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent
// [PointerEvent]: https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent
// [TouchEvent]: https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent
// [WheelEvent]: https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent
// [locators]: https://playwright.dev/docs/locators
DispatchEvent(typ string, eventInit ...interface{}) error
// Returns the return value of “[object Object]”.
// The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
// first argument to “[object Object]”. If no elements match the selector, the method throws an error.
// If “[object Object]” returns a [Promise], then [ElementHandle.EvalOnSelector] would wait for the promise to resolve
// and return its value.
//
// Deprecated: This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests. Use [Locator.Evaluate], other [Locator] helper methods or web-first assertions instead.
//
// 1. selector: A selector to query for.
// 2. expression: JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
// function is automatically invoked.
// 3. arg: Optional argument to pass to “[object Object]”.
EvalOnSelector(selector string, expression string, arg ...interface{}) (interface{}, error)
// Returns the return value of “[object Object]”.
// The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
// of matched elements as a first argument to “[object Object]”.
// If “[object Object]” returns a [Promise], then [ElementHandle.EvalOnSelectorAll] would wait for the promise to
// resolve and return its value.
//
// Deprecated: In most cases, [Locator.EvaluateAll], other [Locator] helper methods and web-first assertions do a better job.
//
// 1. selector: A selector to query for.
// 2. expression: JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the
// function is automatically invoked.
// 3. arg: Optional argument to pass to “[object Object]”.
EvalOnSelectorAll(selector string, expression string, arg ...interface{}) (interface{}, error)
// This method 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 ``, `