package playwright type BindingCall interface { Call(f BindingCallFunction) } // A Browser is created via BrowserType.launch(). An example of using a `Browser` to create a `Page`: type Browser interface { EventEmitter // 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. // The `Browser` object itself is considered to be disposed and cannot be used anymore. Close() 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 // Creates a new browser context. It won't share cookies/cache with other browser contexts. 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 ...BrowserNewContextOptions) (Page, error) // > NOTE: CDP Sessions are only supported on Chromium-based browsers. // Returns the newly created browser session. NewBrowserCDPSession() (CDPSession, error) // Returns the browser version. Version() 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](https://chromedevtools.github.io/devtools-protocol/). // - Getting Started with DevTools Protocol: // https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md 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 Send(method string, params map[string]interface{}) (interface{}, error) } // 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 "incognito" browser contexts with Browser.newContext() method. "Incognito" browser // contexts don't write any browsing data to disk. type BrowserContext interface { EventEmitter // 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 ...BrowserContextAddCookiesOptionsCookies) 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`. // An example of overriding `Math.random` before the page loads: // > NOTE: The order of evaluation of multiple scripts installed via BrowserContext.addInitScript() and // Page.addInitScript() is not defined. AddInitScript(script BrowserContextAddInitScriptOptions) error // Returns the browser instance of the context. If it was launched as a persistent context null gets returned. Browser() Browser // Clears context cookies. ClearCookies() 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() 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) ([]*BrowserContextCookiesResult, error) ExpectEvent(event string, cb func() error) (interface{}, error) // The method adds a function called `name` on the `window` object of every frame in every page in the context. 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 Page.exposeBinding() for page-only version. // An example of exposing page URL to all frames in all pages in the context: // An example of passing an element handle: ExposeBinding(name string, binding BindingCallFunction, handle ...bool) error // The method adds a function called `name` on the `window` object of every frame in every page in the context. 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 Page.exposeFunction() for page-only version. // An example of adding a `sha256` function to all pages in the context: ExposeFunction(name string, binding ExposedFunction) error // Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if // specified. GrantPermissions(permissions []string, options ...BrowserContextGrantPermissionsOptions) error // > NOTE: CDP sessions are only supported on Chromium-based browsers. // Returns the newly created session. NewCDPSession(page Page) (CDPSession, error) // Creates a new page in the browser context. NewPage(options ...BrowserNewPageOptions) (Page, error) // Returns all open pages in the context. Pages() []Page // 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.waitForNavigation() // > NOTE: Page.setDefaultNavigationTimeout`] and [`method: Page.setDefaultTimeout() take priority over // BrowserContext.setDefaultNavigationTimeout(). SetDefaultNavigationTimeout(timeout float64) // This setting will change the default maximum time for all the methods accepting `timeout` option. // > NOTE: Page.setDefaultNavigationTimeout`], [`method: Page.setDefaultTimeout() and // BrowserContext.setDefaultNavigationTimeout`] take priority over [`method: BrowserContext.setDefaultTimeout(). 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. SetExtraHTTPHeaders(headers map[string]string) error // Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable. // > NOTE: Consider using BrowserContext.grantPermissions() to grant permissions for the browser context pages to // read its geolocation. SetGeolocation(gelocation *SetGeolocationOptions) error ResetGeolocation() error // 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: Page.route() will not intercept requests intercepted by Service Worker. See // [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using // request interception. Via `await context.addInitScript(() => delete window.navigator.serviceWorker);` // An example of a naive handler that aborts all image requests: // or the same snippet using a regex pattern instead: // It is possible to examine the request to decide the route action. For example, mocking all requests that contain some // post data, and leaving all other requests as is: // Page routes (set up with Page.route()) take precedence over browser context routes when request matches both // handlers. // To remove a route with its handler you can use BrowserContext.unroute(). // > NOTE: Enabling routing disables http cache. Route(url interface{}, handler routeHandler) error SetOffline(offline bool) error // Returns storage state for this browser context, contains current cookies and local storage snapshot. StorageState(path ...string) (*StorageState, error) // Removes a route created with BrowserContext.route(). When `handler` is not specified, removes all routes for // the `url`. Unroute(url interface{}, handler ...routeHandler) 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. WaitForEvent(event string, predicate ...interface{}) interface{} Tracing() Tracing // > NOTE: Background pages are only supported on Chromium-based browsers. // All existing background pages in the context. BackgroundPages() []Page } // API for collecting and saving Playwright traces. Playwright traces can be opened in [Trace Viewer](./trace-viewer.md) // after Playwright script runs. // Start recording a trace before performing actions. At the end, stop tracing and save it to a file. type Tracing interface { // Start tracing. Start(options ...TracingStartOptions) error // Stop tracing. Stop(options ...TracingStopOptions) error // Start a new trace chunk. If you'd like to record multiple traces on the same `BrowserContext`, use // Tracing.start`] once, and then create multiple trace chunks with [`method: Tracing.startChunk() and // Tracing.stopChunk(). StartChunk(options ...TracingStartChunkOptions) error // Stop the trace chunk. See Tracing.startChunk() for more details about multiple trace chunks. StopChunk(options ...TracingStopChunkOptions) 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 { // A path where Playwright expects to find a bundled browser executable. ExecutablePath() string // Returns the browser instance. // You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments: // > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it works // best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use // `executablePath` option with extreme caution. // > // > If Google Chrome (rather than Chromium) is preferred, a // [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or // [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested. // > // > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs for // video playback. See // [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for other // differences between Chromium and Chrome. // [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md) // describes some differences for Linux users. Launch(options ...BrowserTypeLaunchOptions) (Browser, error) // Returns the persistent browser context instance. // Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this // context will automatically close the browser. LaunchPersistentContext(userDataDir string, options ...BrowserTypeLaunchPersistentContextOptions) (BrowserContext, error) // Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`. Name() string // This methods attaches Playwright to an existing browser instance. Connect(url string, options ...BrowserTypeConnectOptions) (Browser, error) // This methods 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. ConnectOverCDP(endpointURL string, options ...BrowserTypeConnectOverCDPOptions) (Browser, error) } // `ConsoleMessage` objects are dispatched by page via the [`event: Page.console`] event. type ConsoleMessage interface { // List of arguments passed to a `console` function call. See also [`event: Page.console`]. Args() []JSHandle Location() ConsoleMessageLocation String() string // The text of the console message. Text() 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 [`event: Page.dialog`] event. // An example of using `Dialog` class: // > NOTE: Dialogs are dismissed automatically, unless there is a [`event: Page.dialog`] listener. When listener is // present, it **must** either Dialog.accept`] or [`method: Dialog.dismiss() the dialog - otherwise the page will // [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog, and // actions like click will never finish. type Dialog interface { // Returns when the dialog has been accepted. Accept(texts ...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 // Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. Type() string } // `Download` objects are dispatched by page via the [`event: Page.download`] 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 { // 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() (string, error) // Returns path to the downloaded file in case of successful 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. SaveAs(path string) error String() string // Returns suggested filename for this download. It is typically computed by the browser from the // [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header // or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different // browsers can use different logic for computing it. SuggestedFilename() string // Returns downloaded url. URL() string // Get the page that the download belongs to. Page() Page // 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 } // 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 [`method: 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 bonding box, similarly to // [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/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. 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. // 1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set. // 1. Scroll the element into view if needed. // 1. Use [`property: Page.mouse`] to click in the center of the element. // 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. // 1. 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 `timeout`, this method throws a `TimeoutError`. Passing // zero timeout disables this. Check(options ...ElementHandleCheckOptions) error // This method checks or unchecks an element by performing the following steps: // 1. Ensure that element is a checkbox or a radio input. If not, this method throws. // 1. If the element already has the right checked state, this method returns immediately. // 1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the // element is detached during the checks, the whole action is retried. // 1. Scroll the element into view if needed. // 1. Use [`property: Page.mouse`] to click in the center of the element. // 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. // 1. Ensure that the element is now checked or unchecked. If not, this method throws. // When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing // zero timeout disables this. SetChecked(checked bool, options ...ElementHandleSetCheckedOptions) error // This method clicks the element by performing the following steps: // 1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set. // 1. Scroll the element into view if needed. // 1. Use [`property: Page.mouse`] to click in the center of the element, or the specified `position`. // 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` 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 `timeout`, this method throws a `TimeoutError`. Passing // zero timeout disables this. 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](./actionability.md) checks on the element, unless `force` option is set. // 1. Scroll the element into view if needed. // 1. Use [`property: Page.mouse`] to double click in the center of the element, or the specified `position`. // 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. Note that if the // first click of the `dblclick()` triggers a navigation event, this method will throw. // 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 `timeout`, this method throws a `TimeoutError`. Passing // zero timeout disables this. // > NOTE: `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event. 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()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click). // Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit` properties // and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default. // Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties: // - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent) // - [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) // - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event) // You can also specify `JSHandle` as the property value if you want live objects to be passed into the event: DispatchEvent(typ string, initObjects ...interface{}) error // Returns the return value of `expression`. // The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first // argument to `expression`. See [Working with selectors](./selectors.md) for more details. If no elements match the // selector, the method throws an error. // If `expression` returns a [Promise], then ElementHandle.evalOnSelector() would wait for the promise to resolve // and return its value. // Examples: EvalOnSelector(selector string, expression string, options ...interface{}) (interface{}, error) // Returns the return value of `expression`. // 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 `expression`. See [Working with selectors](./selectors.md) for more details. // If `expression` returns a [Promise], then ElementHandle.evalOnSelectorAll() would wait for the promise to // resolve and return its value. // Examples: // ```html //
//
Hello!
//
Hi!
//
// ``` EvalOnSelectorAll(selector string, expression string, options ...interface{}) (interface{}, error) // This method waits for [actionability](./actionability.md) 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 ``, `