// This file is generated by /utils/generate_types/index.js /** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Protocol } from './protocol'; import { ChildProcess } from 'child_process'; import { EventEmitter } from 'events'; import { Readable } from 'stream'; import { Serializable, EvaluationArgument, PageFunction, PageFunctionOn, SmartHandle, ElementHandleForTag, BindingSource } from './structs'; type PageWaitForSelectorOptionsNotHidden = PageWaitForSelectorOptions & { state: 'visible'|'attached'; }; type ElementHandleWaitForSelectorOptionsNotHidden = ElementHandleWaitForSelectorOptions & { state: 'visible'|'attached'; }; /** * - extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) * * Page provides methods to interact with a single tab in a [Browser], or an * [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser] * instance might have multiple [Page] instances. * * This example creates a page, navigates it to a URL, and then saves a screenshot: * * ```js * const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. * * (async () => { * const browser = await webkit.launch(); * const context = await browser.newContext(); * const page = await context.newPage(); * await page.goto('https://example.com'); * await page.screenshot({path: 'screenshot.png'}); * await browser.close(); * })(); * ``` * * The Page class emits various events (described below) which can be handled using any of Node's native * [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or * `removeListener`. * * This example logs a message for a single page `load` event: * * ```js * page.once('load', () => console.log('Page loaded!')); * ``` * * To unsubscribe from events use the `removeListener` method: * * ```js * function logRequest(interceptedRequest) { * console.log('A request was made:', interceptedRequest.url()); * } * page.on('request', logRequest); * // Sometime later... * page.removeListener('request', logRequest); * ``` * */ export interface Page { /** * Returns the value of the `pageFunction` invocation. * * If the function passed to the `page.evaluate` returns a [Promise], then `page.evaluate` would wait for the promise to * resolve and return its value. * * If the function passed to the `page.evaluate` returns a non-[Serializable] value, then `page.evaluate` resolves to * `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: * `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals. * * Passing argument to `pageFunction`: * * ```js * const result = await page.evaluate(([x, y]) => { * return Promise.resolve(x * y); * }, [7, 8]); * console.log(result); // prints "56" * ``` * * A string can also be passed in instead of a function: * * ```js * console.log(await page.evaluate('1 + 2')); // prints "3" * const x = 10; * console.log(await page.evaluate(`1 + ${x}`)); // prints "11" * ``` * * [ElementHandle] instances can be passed as an argument to the `page.evaluate`: * * ```js * const bodyHandle = await page.$('body'); * const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']); * await bodyHandle.dispose(); * ``` * * Shortcut for main frame's * [frame.evaluate(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameevaluate). * @param pageFunction Function to be evaluated in the page context * @param arg Optional argument to pass to `pageFunction` */ evaluate(pageFunction: PageFunction, arg: Arg): Promise; evaluate(pageFunction: PageFunction, arg?: any): Promise; /** * Returns the value of the `pageFunction` invocation as in-page object (JSHandle). * * The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page * object (JSHandle). * * If the function passed to the `page.evaluateHandle` returns a [Promise], then `page.evaluateHandle` would wait for the * promise to resolve and return its value. * * A string can also be passed in instead of a function: * * ```js * const aHandle = await page.evaluateHandle('document'); // Handle for the 'document' * ``` * * [JSHandle] instances can be passed as an argument to the `page.evaluateHandle`: * * ```js * const aHandle = await page.evaluateHandle(() => document.body); * const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle); * console.log(await resultHandle.jsonValue()); * await resultHandle.dispose(); * ``` * * @param pageFunction Function to be evaluated in the page context * @param arg Optional argument to pass to `pageFunction` */ evaluateHandle(pageFunction: PageFunction, arg: Arg): Promise>; evaluateHandle(pageFunction: PageFunction, arg?: any): Promise>; /** * The method finds an element matching the specified selector within the page. If no elements match the selector, the * return value resolves to `null`. * * Shortcut for main frame's [frame.$(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frame). * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. */ $(selector: K): Promise | null>; $(selector: string): Promise | null>; /** * The method finds all elements matching the specified selector within the page. If no elements match the selector, the * return value resolves to `[]`. * * Shortcut for main frame's [frame.$$(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frame). * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. */ $$(selector: K): Promise[]>; $$(selector: string): Promise[]>; /** * The method finds an element matching the specified selector within the page and passes it as a first argument to * `pageFunction`. If no elements match the selector, the method throws an error. Returns the value of `pageFunction`. * * If `pageFunction` returns a [Promise], then * [page.$eval(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageeval) would wait for the promise to * resolve and return its value. * * Examples: * * ```js * const searchValue = await page.$eval('#search', el => el.value); * const preloadHref = await page.$eval('link[rel=preload]', el => el.href); * const html = await page.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello'); * ``` * * Shortcut for main frame's [frame.$eval(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameeval). * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. * @param pageFunction Function to be evaluated in browser context * @param arg Optional argument to pass to `pageFunction` */ $eval(selector: K, pageFunction: PageFunctionOn, arg: Arg): Promise; $eval(selector: string, pageFunction: PageFunctionOn, arg: Arg): Promise; $eval(selector: K, pageFunction: PageFunctionOn, arg?: any): Promise; $eval(selector: string, pageFunction: PageFunctionOn, arg?: any): Promise; /** * The method finds all elements matching the specified selector within the page and passes an array of matched elements as * a first argument to `pageFunction`. Returns the result of `pageFunction` invocation. * * If `pageFunction` returns a [Promise], then * [page.$$eval(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageeval) would wait for the promise to * resolve and return its value. * * Examples: * * ```js * const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); * ``` * * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. * @param pageFunction Function to be evaluated in browser context * @param arg Optional argument to pass to `pageFunction` */ $$eval(selector: K, pageFunction: PageFunctionOn, arg: Arg): Promise; $$eval(selector: string, pageFunction: PageFunctionOn, arg: Arg): Promise; $$eval(selector: K, pageFunction: PageFunctionOn, arg?: any): Promise; $$eval(selector: string, pageFunction: PageFunctionOn, arg?: any): Promise; /** * Returns when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value. * * The `waitForFunction` can be used to observe viewport size change: * * ```js * const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. * * (async () => { * const browser = await webkit.launch(); * const page = await browser.newPage(); * const watchDog = page.waitForFunction('window.innerWidth < 100'); * await page.setViewportSize({width: 50, height: 50}); * await watchDog; * await browser.close(); * })(); * ``` * * To pass an argument to the predicate of `page.waitForFunction` function: * * ```js * const selector = '.foo'; * await page.waitForFunction(selector => !!document.querySelector(selector), selector); * ``` * * Shortcut for main frame's * [frame.waitForFunction(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#framewaitforfunction). * @param pageFunction Function to be evaluated in browser context * @param arg Optional argument to pass to `pageFunction` * @param options */ waitForFunction(pageFunction: PageFunction, arg: Arg, options?: PageWaitForFunctionOptions): Promise>; waitForFunction(pageFunction: PageFunction, arg?: any, options?: PageWaitForFunctionOptions): Promise>; /** * Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or * `detached`. * * Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If at * the moment of calling the method `selector` already satisfies the condition, the method will return immediately. If the * selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw. * * This method works across navigations: * * ```js * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'. * * (async () => { * const browser = await chromium.launch(); * const page = await browser.newPage(); * let currentURL; * page * .waitForSelector('img') * .then(() => console.log('First URL with image: ' + currentURL)); * for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) { * await page.goto(currentURL); * } * await browser.close(); * })(); * ``` * * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. * @param options */ waitForSelector(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise>; waitForSelector(selector: string, options?: PageWaitForSelectorOptionsNotHidden): Promise>; waitForSelector(selector: K, options: PageWaitForSelectorOptions): Promise | null>; waitForSelector(selector: string, options: PageWaitForSelectorOptions): Promise>; /** * The method adds a function called `name` on the `window` object of every frame in this page. When called, the function * executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the `callback` returns * a [Promise], it will be awaited. * * The first argument of the `callback` function contains information about the caller: `{ browserContext: BrowserContext, * page: Page, frame: Frame }`. * * See * [browserContext.exposeBinding(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextexposebinding) * for the context-wide version. * * > **NOTE** Functions installed via `page.exposeBinding` survive navigations. * * An example of exposing page URL to all frames in a page: * * ```js * const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. * * (async () => { * const browser = await webkit.launch({ headless: false }); * const context = await browser.newContext(); * const page = await context.newPage(); * await page.exposeBinding('pageURL', ({ page }) => page.url()); * await page.setContent(` * * *
* `); * await page.click('button'); * })(); * ``` * * An example of passing an element handle: * * ```js * await page.exposeBinding('clicked', async (source, element) => { * console.log(await element.textContent()); * }, { handle: true }); * await page.setContent(` * *
Click me
*
Or click me
* `); * ``` * * @param name Name of the function on the window object. * @param callback Callback function that will be called in the Playwright's context. * @param options */ exposeBinding(name: string, playwrightBinding: (source: BindingSource, arg: JSHandle) => any, options: { handle: true }): Promise; exposeBinding(name: string, playwrightBinding: (source: BindingSource, ...args: any[]) => any, options?: { handle?: boolean }): Promise; /** * Emitted when the page closes. */ on(event: 'close', listener: () => void): this; /** * Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also * emitted if the page throws an error or a warning. * * The arguments passed into `console.log` appear as arguments on the event handler. * * An example of handling `console` event: * * ```js * page.on('console', msg => { * for (let i = 0; i < msg.args().length; ++i) * console.log(`${i}: ${msg.args()[i]}`); * }); * page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); * ``` * */ on(event: 'console', listener: (consoleMessage: ConsoleMessage) => void): this; /** * Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, * ongoing and subsequent operations will throw. * * The most common way to deal with crashes is to catch an exception: * * ```js * try { * // Crash might happen during a click. * await page.click('button'); * // Or while waiting for an event. * await page.waitForEvent('popup'); * } catch (e) { * // When the page crashes, exception message contains 'crash'. * } * ``` * * However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, * handling `crash` event helps: * * ```js * await new Promise((resolve, reject) => { * page.on('requestfinished', async request => { * if (await someProcessing(request)) * resolve(request); * }); * page.on('crash', error => reject(error)); * }); * ``` * */ on(event: 'crash', listener: () => void): this; /** * Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond * to the dialog via [dialog.accept(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogaccept) or * [dialog.dismiss(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogdismiss) methods. */ on(event: 'dialog', listener: (dialog: Dialog) => void): this; /** * Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) * event is dispatched. */ on(event: 'domcontentloaded', listener: () => void): this; /** * Emitted when attachment download started. User can access basic file operations on downloaded content via the passed * [Download] instance. * * > **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the * downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual * download is not performed and user has no access to the downloaded files. */ on(event: 'download', listener: (download: Download) => void): this; /** * Emitted when a file chooser is supposed to appear, such as after clicking the ``. Playwright can * respond to it via setting the input files using * [fileChooser.setFiles(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#filechoosersetfiles) that can * be uploaded after that. * * ```js * page.on('filechooser', async (fileChooser) => { * await fileChooser.setFiles('/tmp/myfile.pdf'); * }); * ``` * */ on(event: 'filechooser', listener: (fileChooser: FileChooser) => void): this; /** * Emitted when a frame is attached. */ on(event: 'frameattached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is detached. */ on(event: 'framedetached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is navigated to a new url. */ on(event: 'framenavigated', listener: (frame: Frame) => void): this; /** * Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. */ on(event: 'load', listener: () => void): this; /** * Emitted when an uncaught exception happens within the page. */ on(event: 'pageerror', listener: (error: Error) => void): this; /** * Emitted when the page opens a new tab or window. This event is emitted in addition to the * [browserContext.on('page')](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextonpage), but * only for popups relevant to this 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. * * ```js * const [popup] = await Promise.all([ * page.waitForEvent('popup'), * page.evaluate(() => window.open('https://example.com')), * ]); * console.log(await popup.evaluate('location.href')); * ``` * * > **NOTE** Use * [page.waitForLoadState(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitforloadstate) to wait * until the page gets to a particular state (you should not need it in most cases). */ on(event: 'popup', listener: (page: Page) => void): this; /** * Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see * [page.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageroute) or * [browserContext.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextroute). */ on(event: 'request', listener: (request: Request) => void): this; /** * Emitted when a request fails, for example by timing out. * * > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request * will complete with * [page.on('requestfinished')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfinished) * event and not with * [page.on('requestfailed')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfailed). */ on(event: 'requestfailed', listener: (request: Request) => void): this; /** * Emitted when a request finishes successfully after downloading the response body. For a successful response, the * sequence of events is `request`, `response` and `requestfinished`. */ on(event: 'requestfinished', listener: (request: Request) => void): this; /** * Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events * is `request`, `response` and `requestfinished`. */ on(event: 'response', listener: (response: Response) => void): this; /** * Emitted when <[WebSocket]> request is sent. */ on(event: 'websocket', listener: (webSocket: WebSocket) => void): this; /** * Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the * page. */ on(event: 'worker', listener: (worker: Worker) => void): this; /** * Emitted when the page closes. */ once(event: 'close', listener: () => void): this; /** * Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also * emitted if the page throws an error or a warning. * * The arguments passed into `console.log` appear as arguments on the event handler. * * An example of handling `console` event: * * ```js * page.on('console', msg => { * for (let i = 0; i < msg.args().length; ++i) * console.log(`${i}: ${msg.args()[i]}`); * }); * page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); * ``` * */ once(event: 'console', listener: (consoleMessage: ConsoleMessage) => void): this; /** * Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, * ongoing and subsequent operations will throw. * * The most common way to deal with crashes is to catch an exception: * * ```js * try { * // Crash might happen during a click. * await page.click('button'); * // Or while waiting for an event. * await page.waitForEvent('popup'); * } catch (e) { * // When the page crashes, exception message contains 'crash'. * } * ``` * * However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, * handling `crash` event helps: * * ```js * await new Promise((resolve, reject) => { * page.on('requestfinished', async request => { * if (await someProcessing(request)) * resolve(request); * }); * page.on('crash', error => reject(error)); * }); * ``` * */ once(event: 'crash', listener: () => void): this; /** * Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond * to the dialog via [dialog.accept(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogaccept) or * [dialog.dismiss(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogdismiss) methods. */ once(event: 'dialog', listener: (dialog: Dialog) => void): this; /** * Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) * event is dispatched. */ once(event: 'domcontentloaded', listener: () => void): this; /** * Emitted when attachment download started. User can access basic file operations on downloaded content via the passed * [Download] instance. * * > **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the * downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual * download is not performed and user has no access to the downloaded files. */ once(event: 'download', listener: (download: Download) => void): this; /** * Emitted when a file chooser is supposed to appear, such as after clicking the ``. Playwright can * respond to it via setting the input files using * [fileChooser.setFiles(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#filechoosersetfiles) that can * be uploaded after that. * * ```js * page.on('filechooser', async (fileChooser) => { * await fileChooser.setFiles('/tmp/myfile.pdf'); * }); * ``` * */ once(event: 'filechooser', listener: (fileChooser: FileChooser) => void): this; /** * Emitted when a frame is attached. */ once(event: 'frameattached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is detached. */ once(event: 'framedetached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is navigated to a new url. */ once(event: 'framenavigated', listener: (frame: Frame) => void): this; /** * Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. */ once(event: 'load', listener: () => void): this; /** * Emitted when an uncaught exception happens within the page. */ once(event: 'pageerror', listener: (error: Error) => void): this; /** * Emitted when the page opens a new tab or window. This event is emitted in addition to the * [browserContext.on('page')](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextonpage), but * only for popups relevant to this 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. * * ```js * const [popup] = await Promise.all([ * page.waitForEvent('popup'), * page.evaluate(() => window.open('https://example.com')), * ]); * console.log(await popup.evaluate('location.href')); * ``` * * > **NOTE** Use * [page.waitForLoadState(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitforloadstate) to wait * until the page gets to a particular state (you should not need it in most cases). */ once(event: 'popup', listener: (page: Page) => void): this; /** * Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see * [page.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageroute) or * [browserContext.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextroute). */ once(event: 'request', listener: (request: Request) => void): this; /** * Emitted when a request fails, for example by timing out. * * > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request * will complete with * [page.on('requestfinished')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfinished) * event and not with * [page.on('requestfailed')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfailed). */ once(event: 'requestfailed', listener: (request: Request) => void): this; /** * Emitted when a request finishes successfully after downloading the response body. For a successful response, the * sequence of events is `request`, `response` and `requestfinished`. */ once(event: 'requestfinished', listener: (request: Request) => void): this; /** * Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events * is `request`, `response` and `requestfinished`. */ once(event: 'response', listener: (response: Response) => void): this; /** * Emitted when <[WebSocket]> request is sent. */ once(event: 'websocket', listener: (webSocket: WebSocket) => void): this; /** * Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the * page. */ once(event: 'worker', listener: (worker: Worker) => void): this; /** * Emitted when the page closes. */ addListener(event: 'close', listener: () => void): this; /** * Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also * emitted if the page throws an error or a warning. * * The arguments passed into `console.log` appear as arguments on the event handler. * * An example of handling `console` event: * * ```js * page.on('console', msg => { * for (let i = 0; i < msg.args().length; ++i) * console.log(`${i}: ${msg.args()[i]}`); * }); * page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); * ``` * */ addListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => void): this; /** * Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, * ongoing and subsequent operations will throw. * * The most common way to deal with crashes is to catch an exception: * * ```js * try { * // Crash might happen during a click. * await page.click('button'); * // Or while waiting for an event. * await page.waitForEvent('popup'); * } catch (e) { * // When the page crashes, exception message contains 'crash'. * } * ``` * * However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, * handling `crash` event helps: * * ```js * await new Promise((resolve, reject) => { * page.on('requestfinished', async request => { * if (await someProcessing(request)) * resolve(request); * }); * page.on('crash', error => reject(error)); * }); * ``` * */ addListener(event: 'crash', listener: () => void): this; /** * Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond * to the dialog via [dialog.accept(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogaccept) or * [dialog.dismiss(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogdismiss) methods. */ addListener(event: 'dialog', listener: (dialog: Dialog) => void): this; /** * Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) * event is dispatched. */ addListener(event: 'domcontentloaded', listener: () => void): this; /** * Emitted when attachment download started. User can access basic file operations on downloaded content via the passed * [Download] instance. * * > **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the * downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual * download is not performed and user has no access to the downloaded files. */ addListener(event: 'download', listener: (download: Download) => void): this; /** * Emitted when a file chooser is supposed to appear, such as after clicking the ``. Playwright can * respond to it via setting the input files using * [fileChooser.setFiles(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#filechoosersetfiles) that can * be uploaded after that. * * ```js * page.on('filechooser', async (fileChooser) => { * await fileChooser.setFiles('/tmp/myfile.pdf'); * }); * ``` * */ addListener(event: 'filechooser', listener: (fileChooser: FileChooser) => void): this; /** * Emitted when a frame is attached. */ addListener(event: 'frameattached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is detached. */ addListener(event: 'framedetached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is navigated to a new url. */ addListener(event: 'framenavigated', listener: (frame: Frame) => void): this; /** * Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. */ addListener(event: 'load', listener: () => void): this; /** * Emitted when an uncaught exception happens within the page. */ addListener(event: 'pageerror', listener: (error: Error) => void): this; /** * Emitted when the page opens a new tab or window. This event is emitted in addition to the * [browserContext.on('page')](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextonpage), but * only for popups relevant to this 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. * * ```js * const [popup] = await Promise.all([ * page.waitForEvent('popup'), * page.evaluate(() => window.open('https://example.com')), * ]); * console.log(await popup.evaluate('location.href')); * ``` * * > **NOTE** Use * [page.waitForLoadState(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitforloadstate) to wait * until the page gets to a particular state (you should not need it in most cases). */ addListener(event: 'popup', listener: (page: Page) => void): this; /** * Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see * [page.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageroute) or * [browserContext.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextroute). */ addListener(event: 'request', listener: (request: Request) => void): this; /** * Emitted when a request fails, for example by timing out. * * > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request * will complete with * [page.on('requestfinished')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfinished) * event and not with * [page.on('requestfailed')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfailed). */ addListener(event: 'requestfailed', listener: (request: Request) => void): this; /** * Emitted when a request finishes successfully after downloading the response body. For a successful response, the * sequence of events is `request`, `response` and `requestfinished`. */ addListener(event: 'requestfinished', listener: (request: Request) => void): this; /** * Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events * is `request`, `response` and `requestfinished`. */ addListener(event: 'response', listener: (response: Response) => void): this; /** * Emitted when <[WebSocket]> request is sent. */ addListener(event: 'websocket', listener: (webSocket: WebSocket) => void): this; /** * Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the * page. */ addListener(event: 'worker', listener: (worker: Worker) => void): this; /** * Emitted when the page closes. */ removeListener(event: 'close', listener: () => void): this; /** * Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also * emitted if the page throws an error or a warning. * * The arguments passed into `console.log` appear as arguments on the event handler. * * An example of handling `console` event: * * ```js * page.on('console', msg => { * for (let i = 0; i < msg.args().length; ++i) * console.log(`${i}: ${msg.args()[i]}`); * }); * page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); * ``` * */ removeListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => void): this; /** * Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, * ongoing and subsequent operations will throw. * * The most common way to deal with crashes is to catch an exception: * * ```js * try { * // Crash might happen during a click. * await page.click('button'); * // Or while waiting for an event. * await page.waitForEvent('popup'); * } catch (e) { * // When the page crashes, exception message contains 'crash'. * } * ``` * * However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, * handling `crash` event helps: * * ```js * await new Promise((resolve, reject) => { * page.on('requestfinished', async request => { * if (await someProcessing(request)) * resolve(request); * }); * page.on('crash', error => reject(error)); * }); * ``` * */ removeListener(event: 'crash', listener: () => void): this; /** * Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond * to the dialog via [dialog.accept(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogaccept) or * [dialog.dismiss(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogdismiss) methods. */ removeListener(event: 'dialog', listener: (dialog: Dialog) => void): this; /** * Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) * event is dispatched. */ removeListener(event: 'domcontentloaded', listener: () => void): this; /** * Emitted when attachment download started. User can access basic file operations on downloaded content via the passed * [Download] instance. * * > **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the * downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual * download is not performed and user has no access to the downloaded files. */ removeListener(event: 'download', listener: (download: Download) => void): this; /** * Emitted when a file chooser is supposed to appear, such as after clicking the ``. Playwright can * respond to it via setting the input files using * [fileChooser.setFiles(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#filechoosersetfiles) that can * be uploaded after that. * * ```js * page.on('filechooser', async (fileChooser) => { * await fileChooser.setFiles('/tmp/myfile.pdf'); * }); * ``` * */ removeListener(event: 'filechooser', listener: (fileChooser: FileChooser) => void): this; /** * Emitted when a frame is attached. */ removeListener(event: 'frameattached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is detached. */ removeListener(event: 'framedetached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is navigated to a new url. */ removeListener(event: 'framenavigated', listener: (frame: Frame) => void): this; /** * Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. */ removeListener(event: 'load', listener: () => void): this; /** * Emitted when an uncaught exception happens within the page. */ removeListener(event: 'pageerror', listener: (error: Error) => void): this; /** * Emitted when the page opens a new tab or window. This event is emitted in addition to the * [browserContext.on('page')](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextonpage), but * only for popups relevant to this 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. * * ```js * const [popup] = await Promise.all([ * page.waitForEvent('popup'), * page.evaluate(() => window.open('https://example.com')), * ]); * console.log(await popup.evaluate('location.href')); * ``` * * > **NOTE** Use * [page.waitForLoadState(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitforloadstate) to wait * until the page gets to a particular state (you should not need it in most cases). */ removeListener(event: 'popup', listener: (page: Page) => void): this; /** * Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see * [page.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageroute) or * [browserContext.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextroute). */ removeListener(event: 'request', listener: (request: Request) => void): this; /** * Emitted when a request fails, for example by timing out. * * > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request * will complete with * [page.on('requestfinished')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfinished) * event and not with * [page.on('requestfailed')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfailed). */ removeListener(event: 'requestfailed', listener: (request: Request) => void): this; /** * Emitted when a request finishes successfully after downloading the response body. For a successful response, the * sequence of events is `request`, `response` and `requestfinished`. */ removeListener(event: 'requestfinished', listener: (request: Request) => void): this; /** * Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events * is `request`, `response` and `requestfinished`. */ removeListener(event: 'response', listener: (response: Response) => void): this; /** * Emitted when <[WebSocket]> request is sent. */ removeListener(event: 'websocket', listener: (webSocket: WebSocket) => void): this; /** * Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the * page. */ removeListener(event: 'worker', listener: (worker: Worker) => void): this; /** * Emitted when the page closes. */ off(event: 'close', listener: () => void): this; /** * Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also * emitted if the page throws an error or a warning. * * The arguments passed into `console.log` appear as arguments on the event handler. * * An example of handling `console` event: * * ```js * page.on('console', msg => { * for (let i = 0; i < msg.args().length; ++i) * console.log(`${i}: ${msg.args()[i]}`); * }); * page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); * ``` * */ off(event: 'console', listener: (consoleMessage: ConsoleMessage) => void): this; /** * Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, * ongoing and subsequent operations will throw. * * The most common way to deal with crashes is to catch an exception: * * ```js * try { * // Crash might happen during a click. * await page.click('button'); * // Or while waiting for an event. * await page.waitForEvent('popup'); * } catch (e) { * // When the page crashes, exception message contains 'crash'. * } * ``` * * However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, * handling `crash` event helps: * * ```js * await new Promise((resolve, reject) => { * page.on('requestfinished', async request => { * if (await someProcessing(request)) * resolve(request); * }); * page.on('crash', error => reject(error)); * }); * ``` * */ off(event: 'crash', listener: () => void): this; /** * Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond * to the dialog via [dialog.accept(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogaccept) or * [dialog.dismiss(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#dialogdismiss) methods. */ off(event: 'dialog', listener: (dialog: Dialog) => void): this; /** * Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) * event is dispatched. */ off(event: 'domcontentloaded', listener: () => void): this; /** * Emitted when attachment download started. User can access basic file operations on downloaded content via the passed * [Download] instance. * * > **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the * downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual * download is not performed and user has no access to the downloaded files. */ off(event: 'download', listener: (download: Download) => void): this; /** * Emitted when a file chooser is supposed to appear, such as after clicking the ``. Playwright can * respond to it via setting the input files using * [fileChooser.setFiles(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#filechoosersetfiles) that can * be uploaded after that. * * ```js * page.on('filechooser', async (fileChooser) => { * await fileChooser.setFiles('/tmp/myfile.pdf'); * }); * ``` * */ off(event: 'filechooser', listener: (fileChooser: FileChooser) => void): this; /** * Emitted when a frame is attached. */ off(event: 'frameattached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is detached. */ off(event: 'framedetached', listener: (frame: Frame) => void): this; /** * Emitted when a frame is navigated to a new url. */ off(event: 'framenavigated', listener: (frame: Frame) => void): this; /** * Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. */ off(event: 'load', listener: () => void): this; /** * Emitted when an uncaught exception happens within the page. */ off(event: 'pageerror', listener: (error: Error) => void): this; /** * Emitted when the page opens a new tab or window. This event is emitted in addition to the * [browserContext.on('page')](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextonpage), but * only for popups relevant to this 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. * * ```js * const [popup] = await Promise.all([ * page.waitForEvent('popup'), * page.evaluate(() => window.open('https://example.com')), * ]); * console.log(await popup.evaluate('location.href')); * ``` * * > **NOTE** Use * [page.waitForLoadState(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitforloadstate) to wait * until the page gets to a particular state (you should not need it in most cases). */ off(event: 'popup', listener: (page: Page) => void): this; /** * Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see * [page.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageroute) or * [browserContext.route(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextroute). */ off(event: 'request', listener: (request: Request) => void): this; /** * Emitted when a request fails, for example by timing out. * * > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request * will complete with * [page.on('requestfinished')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfinished) * event and not with * [page.on('requestfailed')](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageonrequestfailed). */ off(event: 'requestfailed', listener: (request: Request) => void): this; /** * Emitted when a request finishes successfully after downloading the response body. For a successful response, the * sequence of events is `request`, `response` and `requestfinished`. */ off(event: 'requestfinished', listener: (request: Request) => void): this; /** * Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events * is `request`, `response` and `requestfinished`. */ off(event: 'response', listener: (response: Response) => void): this; /** * Emitted when <[WebSocket]> request is sent. */ off(event: 'websocket', listener: (webSocket: WebSocket) => void): this; /** * Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the * page. */ off(event: 'worker', listener: (worker: Worker) => void): this; accessibility: Accessibility; /** * Adds a script which would be evaluated in one of the following scenarios: * - Whenever the page is navigated. * - Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly * attached frame. * * The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend * the JavaScript environment, e.g. to seed `Math.random`. * * An example of overriding `Math.random` before the page loads: * * ```js * // preload.js * Math.random = () => 42; * * // In your playwright script, assuming the preload.js file is in same directory * const preloadFile = fs.readFileSync('./preload.js', 'utf8'); * await page.addInitScript(preloadFile); * ``` * * > **NOTE** The order of evaluation of multiple scripts installed via * [browserContext.addInitScript(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsercontextaddinitscript) * and [page.addInitScript(…)](https://github.com/microsoft/playwright/blob/master/docs/api.md#pageaddinitscript) is not * defined. * @param script Script to be evaluated in the page. * @param arg Optional argument to pass to `script` (only supported when passing a function). */ addInitScript(script: Function|string|{ /** * Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working * directory. Optional. */ path?: string; /** * Raw script content. Optional. */ content?: string; }, arg?: Serializable): Promise; /** * Adds a ` * *
* `); * await page.click('button'); * })(); * ``` * * An example of adding a `window.readfile` function to the page: * * ```js * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'. * const fs = require('fs'); * * (async () => { * const browser = await chromium.launch(); * const page = await browser.newPage(); * page.on('console', msg => console.log(msg.text())); * await page.exposeFunction('readfile', async filePath => { * return new Promise((resolve, reject) => { * fs.readFile(filePath, 'utf8', (err, text) => { * if (err) * reject(err); * else * resolve(text); * }); * }); * }); * await page.evaluate(async () => { * // use window.readfile to read contents of a file * const content = await window.readfile('/etc/hosts'); * console.log(content); * }); * await browser.close(); * })(); * ``` * * @param name Name of the function on the window object * @param callback Callback function which will be called in Playwright's context. */ exposeFunction(name: string, callback: Function): Promise; /** * This method waits for an element matching `selector`, waits for [actionability](https://github.com/microsoft/playwright/blob/master/docs/actionability.md) checks, focuses the * element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an ``, * `