1 |
|
2 | # Playwright API <!-- GEN:version -->v1.3.0<!-- GEN:stop-->
|
3 |
|
4 | ##### Table of Contents
|
5 |
|
6 |
|
7 | - [Playwright module](#playwright-module)
|
8 | - [class: Browser](#class-browser)
|
9 | - [class: BrowserContext](#class-browsercontext)
|
10 | - [class: Page](#class-page)
|
11 | - [class: Frame](#class-frame)
|
12 | - [class: ElementHandle](#class-elementhandle)
|
13 | - [class: JSHandle](#class-jshandle)
|
14 | - [class: ConsoleMessage](#class-consolemessage)
|
15 | - [class: Dialog](#class-dialog)
|
16 | - [class: Download](#class-download)
|
17 | - [class: FileChooser](#class-filechooser)
|
18 | - [class: Keyboard](#class-keyboard)
|
19 | - [class: Mouse](#class-mouse)
|
20 | - [class: Request](#class-request)
|
21 | - [class: Response](#class-response)
|
22 | - [class: Selectors](#class-selectors)
|
23 | - [class: Route](#class-route)
|
24 | - [class: TimeoutError](#class-timeouterror)
|
25 | - [class: Accessibility](#class-accessibility)
|
26 | - [class: Worker](#class-worker)
|
27 | - [class: BrowserServer](#class-browserserver)
|
28 | - [class: BrowserType](#class-browsertype)
|
29 | - [class: Logger](#class-logger)
|
30 | - [class: ChromiumBrowser](#class-chromiumbrowser)
|
31 | - [class: ChromiumBrowserContext](#class-chromiumbrowsercontext)
|
32 | - [class: ChromiumCoverage](#class-chromiumcoverage)
|
33 | - [class: CDPSession](#class-cdpsession)
|
34 | - [class: FirefoxBrowser](#class-firefoxbrowser)
|
35 | - [class: WebKitBrowser](#class-webkitbrowser)
|
36 | - [EvaluationArgument](#evaluationargument)
|
37 | - [Environment Variables](#environment-variables)
|
38 | - [Working with selectors](#working-with-selectors)
|
39 | - [Working with Chrome Extensions](#working-with-chrome-extensions)
|
40 |
|
41 |
|
42 | ### Playwright module
|
43 |
|
44 | Playwright module provides a method to launch a browser instance.
|
45 | The following is a typical example of using Playwright to drive automation:
|
46 | ```js
|
47 | const { chromium, firefox, webkit } = require('playwright');
|
48 |
|
49 | (async () => {
|
50 | const browser = await chromium.launch(); // Or 'firefox' or 'webkit'.
|
51 | const page = await browser.newPage();
|
52 | await page.goto('http://example.com');
|
53 | // other actions...
|
54 | await browser.close();
|
55 | })();
|
56 | ```
|
57 |
|
58 | By default, the `playwright` NPM package automatically downloads browser executables during installation. The `playwright-core` NPM package can be used to skip automatic downloads.
|
59 |
|
60 |
|
61 | - [playwright.chromium](#playwrightchromium)
|
62 | - [playwright.devices](#playwrightdevices)
|
63 | - [playwright.errors](#playwrighterrors)
|
64 | - [playwright.firefox](#playwrightfirefox)
|
65 | - [playwright.selectors](#playwrightselectors)
|
66 | - [playwright.webkit](#playwrightwebkit)
|
67 |
|
68 |
|
69 | #### playwright.chromium
|
70 | - returns: <[BrowserType]>
|
71 |
|
72 | This object can be used to launch or connect to Chromium, returning instances of [ChromiumBrowser].
|
73 |
|
74 | #### playwright.devices
|
75 | - returns: <[Object]>
|
76 |
|
77 | Returns a list of devices to be used with [`browser.newContext([options])`](#browsernewcontextoptions) or [`browser.newPage([options])`](#browsernewpageoptions). Actual list of devices can be found in [src/deviceDescriptors.ts](https://github.com/Microsoft/playwright/blob/master/src/deviceDescriptors.ts).
|
78 |
|
79 | ```js
|
80 | const { webkit, devices } = require('playwright');
|
81 | const iPhone = devices['iPhone 6'];
|
82 |
|
83 | (async () => {
|
84 | const browser = await webkit.launch();
|
85 | const context = await browser.newContext({
|
86 | ...iPhone
|
87 | });
|
88 | const page = await context.newPage();
|
89 | await page.goto('http://example.com');
|
90 | // other actions...
|
91 | await browser.close();
|
92 | })();
|
93 | ```
|
94 |
|
95 | #### playwright.errors
|
96 | - returns: <[Object]>
|
97 | - `TimeoutError` <[function]> A class of [TimeoutError].
|
98 |
|
99 | Playwright methods might throw errors if they are unable to fulfill a request. For example, [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options)
|
100 | might fail if the selector doesn't match any nodes during the given timeframe.
|
101 |
|
102 | For certain types of errors Playwright uses specific error classes.
|
103 | These classes are available via [`playwright.errors`](#playwrighterrors).
|
104 |
|
105 | An example of handling a timeout error:
|
106 | ```js
|
107 | try {
|
108 | await page.waitForSelector('.foo');
|
109 | } catch (e) {
|
110 | if (e instanceof playwright.errors.TimeoutError) {
|
111 | // Do something if this is a timeout.
|
112 | }
|
113 | }
|
114 | ```
|
115 |
|
116 | #### playwright.firefox
|
117 | - returns: <[BrowserType]>
|
118 |
|
119 | This object can be used to launch or connect to Firefox, returning instances of [FirefoxBrowser].
|
120 |
|
121 | #### playwright.selectors
|
122 | - returns: <[Selectors]>
|
123 |
|
124 | Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more information.
|
125 |
|
126 | #### playwright.webkit
|
127 | - returns: <[BrowserType]>
|
128 |
|
129 | This object can be used to launch or connect to WebKit, returning instances of [WebKitBrowser].
|
130 |
|
131 |
|
132 | ### class: Browser
|
133 |
|
134 | * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
|
135 |
|
136 | A Browser is created when Playwright connects to a browser instance, either through [`browserType.launch`](#browsertypelaunchoptions) or [`browserType.connect`](#browsertypeconnectoptions).
|
137 |
|
138 | An example of using a [Browser] to create a [Page]:
|
139 | ```js
|
140 | const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
|
141 |
|
142 | (async () => {
|
143 | const browser = await firefox.launch();
|
144 | const page = await browser.newPage();
|
145 | await page.goto('https://example.com');
|
146 | await browser.close();
|
147 | })();
|
148 | ```
|
149 |
|
150 | See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that [browserType.connect(options)](#browsertypeconnectoptions) and [browserType.launch([options])](#browsertypelaunchoptions) always return a specific browser instance, based on the browser being connected to or launched.
|
151 |
|
152 |
|
153 | - [event: 'disconnected'](#event-disconnected)
|
154 | - [browser.close()](#browserclose)
|
155 | - [browser.contexts()](#browsercontexts)
|
156 | - [browser.isConnected()](#browserisconnected)
|
157 | - [browser.newContext([options])](#browsernewcontextoptions)
|
158 | - [browser.newPage([options])](#browsernewpageoptions)
|
159 | - [browser.version()](#browserversion)
|
160 |
|
161 |
|
162 | #### event: 'disconnected'
|
163 | Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:
|
164 | - Browser application is closed or crashed.
|
165 | - The [`browser.close`](#browserclose) method was called.
|
166 |
|
167 | #### browser.close()
|
168 | - returns: <[Promise]>
|
169 |
|
170 | In case this browser is obtained using [browserType.launch](#browsertypelaunchoptions), closes the browser and all of its pages (if any were opened).
|
171 |
|
172 | In case this browser is obtained using [browserType.connect](#browsertypeconnectoptions), clears all created contexts belonging to this browser and disconnects from the browser server.
|
173 |
|
174 | The [Browser] object itself is considered to be disposed and cannot be used anymore.
|
175 |
|
176 | #### browser.contexts()
|
177 | - returns: <[Array]<[BrowserContext]>>
|
178 |
|
179 | Returns an array of all open browser contexts. In a newly created browser, this will return zero
|
180 | browser contexts.
|
181 |
|
182 | ```js
|
183 | const browser = await pw.webkit.launch();
|
184 | console.log(browser.contexts().length); // prints `0`
|
185 |
|
186 | const context = await browser.newContext();
|
187 | console.log(browser.contexts().length); // prints `1`
|
188 | ```
|
189 |
|
190 | #### browser.isConnected()
|
191 |
|
192 | - returns: <[boolean]>
|
193 |
|
194 | Indicates that the browser is connected.
|
195 |
|
196 | #### browser.newContext([options])
|
197 | - `options` <[Object]>
|
198 | - `acceptDownloads` <[boolean]> Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
|
199 | - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
|
200 | - `bypassCSP` <[boolean]> Toggles bypassing page's Content-Security-Policy.
|
201 | - `viewport` <?[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
|
202 | - `width` <[number]> page width in pixels.
|
203 | - `height` <[number]> page height in pixels.
|
204 | - `userAgent` <[string]> Specific user agent to use in this context.
|
205 | - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.
|
206 | - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported in Firefox.
|
207 | - `hasTouch` <[boolean]> Specifies if viewport supports touch events. Defaults to false.
|
208 | - `javaScriptEnabled` <[boolean]> Whether or not to enable JavaScript in the context. Defaults to true.
|
209 | - `timezoneId` <[string]> Changes the timezone of the context. See [ICU’s `metaZones.txt`](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
|
210 | - `geolocation` <[Object]>
|
211 | - `latitude` <[number]> Latitude between -90 and 90.
|
212 | - `longitude` <[number]> Longitude between -180 and 180.
|
213 | - `accuracy` <[number]> Non-negative accuracy value. Defaults to `0`.
|
214 | - `locale` <[string]> Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language` request header value as well as number and date formatting rules.
|
215 | - `permissions` <[Array]<[string]>> A list of permissions to grant to all pages in this context. See [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) for more details.
|
216 | - `extraHTTPHeaders` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
|
217 | - `offline` <[boolean]> Whether to emulate network being offline. Defaults to `false`.
|
218 | - `httpCredentials` <[Object]> Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
|
219 | - `username` <[string]>
|
220 | - `password` <[string]>
|
221 | - `colorScheme` <"light"|"dark"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(options)](#pageemulatemediaoptions) for more details. Defaults to '`light`'.
|
222 | - `logger` <[Logger]> Logger sink for Playwright logging.
|
223 | - returns: <[Promise]<[BrowserContext]>>
|
224 |
|
225 | Creates a new browser context. It won't share cookies/cache with other browser contexts.
|
226 |
|
227 | ```js
|
228 | (async () => {
|
229 | const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'.
|
230 | // Create a new incognito browser context.
|
231 | const context = await browser.newContext();
|
232 | // Create a new page in a pristine context.
|
233 | const page = await context.newPage();
|
234 | await page.goto('https://example.com');
|
235 | })();
|
236 | ```
|
237 |
|
238 | #### browser.newPage([options])
|
239 | - `options` <[Object]>
|
240 | - `acceptDownloads` <[boolean]> Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
|
241 | - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
|
242 | - `bypassCSP` <[boolean]> Toggles bypassing page's Content-Security-Policy.
|
243 | - `viewport` <?[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
|
244 | - `width` <[number]> page width in pixels.
|
245 | - `height` <[number]> page height in pixels.
|
246 | - `userAgent` <[string]> Specific user agent to use in this context.
|
247 | - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.
|
248 | - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported in Firefox.
|
249 | - `hasTouch` <[boolean]> Specifies if viewport supports touch events. Defaults to false.
|
250 | - `javaScriptEnabled` <[boolean]> Whether or not to enable JavaScript in the context. Defaults to `true`.
|
251 | - `timezoneId` <[string]> Changes the timezone of the context. See [ICU’s `metaZones.txt`](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
|
252 | - `geolocation` <[Object]>
|
253 | - `latitude` <[number]> Latitude between -90 and 90.
|
254 | - `longitude` <[number]> Longitude between -180 and 180.
|
255 | - `accuracy` <[number]> Non-negative accuracy value. Defaults to `0`.
|
256 | - `locale` <[string]> Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language` request header value as well as number and date formatting rules.
|
257 | - `permissions` <[Array]<[string]>> A list of permissions to grant to all pages in this context. See [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) for more details.
|
258 | - `extraHTTPHeaders` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
|
259 | - `offline` <[boolean]> Whether to emulate network being offline. Defaults to `false`.
|
260 | - `httpCredentials` <[Object]> Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
|
261 | - `username` <[string]>
|
262 | - `password` <[string]>
|
263 | - `colorScheme` <"light"|"dark"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(options)](#pageemulatemediaoptions) for more details. Defaults to '`light`'.
|
264 | - `logger` <[Logger]> Logger sink for Playwright logging.
|
265 | - returns: <[Promise]<[Page]>>
|
266 |
|
267 | Creates a new page in a new browser context. Closing this page will close the context as well.
|
268 |
|
269 | 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](#browsernewcontextoptions) followed by the [browserContext.newPage](#browsercontextnewpage) to control their exact life times.
|
270 |
|
271 | #### browser.version()
|
272 |
|
273 | - returns: <[string]>
|
274 |
|
275 | Returns the browser version.
|
276 |
|
277 | ### class: BrowserContext
|
278 |
|
279 | * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
|
280 |
|
281 | BrowserContexts provide a way to operate multiple independent browser sessions.
|
282 |
|
283 | If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser
|
284 | context.
|
285 |
|
286 | Playwright allows creation of "incognito" browser contexts with `browser.newContext()` method.
|
287 | "Incognito" browser contexts don't write any browsing data to disk.
|
288 |
|
289 | ```js
|
290 | // Create a new incognito browser context
|
291 | const context = await browser.newContext();
|
292 | // Create a new page inside context.
|
293 | const page = await context.newPage();
|
294 | await page.goto('https://example.com');
|
295 | // Dispose context once it's no longer needed.
|
296 | await context.close();
|
297 | ```
|
298 |
|
299 |
|
300 | - [event: 'close'](#event-close)
|
301 | - [event: 'page'](#event-page)
|
302 | - [browserContext.addCookies(cookies)](#browsercontextaddcookiescookies)
|
303 | - [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg)
|
304 | - [browserContext.clearCookies()](#browsercontextclearcookies)
|
305 | - [browserContext.clearPermissions()](#browsercontextclearpermissions)
|
306 | - [browserContext.close()](#browsercontextclose)
|
307 | - [browserContext.cookies([urls])](#browsercontextcookiesurls)
|
308 | - [browserContext.exposeBinding(name, playwrightBinding)](#browsercontextexposebindingname-playwrightbinding)
|
309 | - [browserContext.exposeFunction(name, playwrightFunction)](#browsercontextexposefunctionname-playwrightfunction)
|
310 | - [browserContext.grantPermissions(permissions[][, options])](#browsercontextgrantpermissionspermissions-options)
|
311 | - [browserContext.newPage()](#browsercontextnewpage)
|
312 | - [browserContext.pages()](#browsercontextpages)
|
313 | - [browserContext.route(url, handler)](#browsercontextrouteurl-handler)
|
314 | - [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout)
|
315 | - [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout)
|
316 | - [browserContext.setExtraHTTPHeaders(headers)](#browsercontextsetextrahttpheadersheaders)
|
317 | - [browserContext.setGeolocation(geolocation)](#browsercontextsetgeolocationgeolocation)
|
318 | - [browserContext.setHTTPCredentials(httpCredentials)](#browsercontextsethttpcredentialshttpcredentials)
|
319 | - [browserContext.setOffline(offline)](#browsercontextsetofflineoffline)
|
320 | - [browserContext.unroute(url[, handler])](#browsercontextunrouteurl-handler)
|
321 | - [browserContext.waitForEvent(event[, optionsOrPredicate])](#browsercontextwaitforeventevent-optionsorpredicate)
|
322 |
|
323 |
|
324 | #### event: 'close'
|
325 |
|
326 | Emitted when Browser context gets closed. This might happen because of one of the following:
|
327 | - Browser context is closed.
|
328 | - Browser application is closed or crashed.
|
329 | - The [`browser.close`](#browserclose) method was called.
|
330 |
|
331 | #### event: 'page'
|
332 | - <[Page]>
|
333 |
|
334 | 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.on('popup')`](#event-popup) to receive events about popups relevant to a specific page.
|
335 |
|
336 | 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.
|
337 |
|
338 | ```js
|
339 | const [page] = await Promise.all([
|
340 | context.waitForEvent('page'),
|
341 | page.click('a[target=_blank]'),
|
342 | ]);
|
343 | console.log(await page.evaluate('location.href'));
|
344 | ```
|
345 |
|
346 | > **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases).
|
347 |
|
348 | #### browserContext.addCookies(cookies)
|
349 | - `cookies` <[Array]<[Object]>>
|
350 | - `name` <[string]> **required**
|
351 | - `value` <[string]> **required**
|
352 | - `url` <[string]> either url or domain / path are required
|
353 | - `domain` <[string]> either url or domain / path are required
|
354 | - `path` <[string]> either url or domain / path are required
|
355 | - `expires` <[number]> Unix time in seconds.
|
356 | - `httpOnly` <[boolean]>
|
357 | - `secure` <[boolean]>
|
358 | - `sameSite` <"Strict"|"Lax"|"None">
|
359 | - returns: <[Promise]>
|
360 |
|
361 | ```js
|
362 | await browserContext.addCookies([cookieObject1, cookieObject2]);
|
363 | ```
|
364 |
|
365 | #### browserContext.addInitScript(script[, arg])
|
366 | - `script` <[function]|[string]|[Object]> Script to be evaluated in all pages in the browser context.
|
367 | - `path` <[string]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
368 | - `content` <[string]> Raw script content.
|
369 | - `arg` <[Serializable]> Optional argument to pass to `script` (only supported when passing a function).
|
370 | - returns: <[Promise]>
|
371 |
|
372 | Adds a script which would be evaluated in one of the following scenarios:
|
373 | - Whenever a page is created in the browser context or is navigated.
|
374 | - 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.
|
375 |
|
376 | 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`.
|
377 |
|
378 | An example of overriding `Math.random` before the page loads:
|
379 |
|
380 | ```js
|
381 | // preload.js
|
382 | Math.random = () => 42;
|
383 | ```
|
384 |
|
385 | ```js
|
386 | // In your playwright script, assuming the preload.js file is in same folder.
|
387 | await browserContext.addInitScript({
|
388 | path: 'preload.js'
|
389 | });
|
390 | ```
|
391 |
|
392 | > **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is not defined.
|
393 | #### browserContext.clearCookies()
|
394 | - returns: <[Promise]>
|
395 |
|
396 | Clears context cookies.
|
397 |
|
398 | #### browserContext.clearPermissions()
|
399 | - returns: <[Promise]>
|
400 |
|
401 | Clears all permission overrides for the browser context.
|
402 |
|
403 | ```js
|
404 | const context = await browser.newContext();
|
405 | await context.grantPermissions(['clipboard-read']);
|
406 | // do stuff ..
|
407 | context.clearPermissions();
|
408 | ```
|
409 |
|
410 | #### browserContext.close()
|
411 | - returns: <[Promise]>
|
412 |
|
413 | Closes the browser context. All the pages that belong to the browser context
|
414 | will be closed.
|
415 |
|
416 | > **NOTE** the default browser context cannot be closed.
|
417 |
|
418 | #### browserContext.cookies([urls])
|
419 | - `urls` <[string]|[Array]<[string]>>
|
420 | - returns: <[Promise]<[Array]<[Object]>>>
|
421 | - `name` <[string]>
|
422 | - `value` <[string]>
|
423 | - `domain` <[string]>
|
424 | - `path` <[string]>
|
425 | - `expires` <[number]> Unix time in seconds.
|
426 | - `httpOnly` <[boolean]>
|
427 | - `secure` <[boolean]>
|
428 | - `sameSite` <"Strict"|"Lax"|"None">
|
429 |
|
430 | If no URLs are specified, this method returns all cookies.
|
431 | If URLs are specified, only cookies that affect those URLs are returned.
|
432 |
|
433 | #### browserContext.exposeBinding(name, playwrightBinding)
|
434 | - `name` <[string]> Name of the function on the window object.
|
435 | - `playwrightBinding` <[function]> Callback function that will be called in the Playwright's context.
|
436 | - returns: <[Promise]>
|
437 |
|
438 | The method adds a function called `name` on the `window` object of every frame in every page in the context.
|
439 | When called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of `playwrightBinding`.
|
440 | If the `playwrightBinding` returns a [Promise], it will be awaited.
|
441 |
|
442 | The first argument of the `playwrightBinding` function contains information about the caller:
|
443 | `{ browserContext: BrowserContext, page: Page, frame: Frame }`.
|
444 |
|
445 | See [page.exposeBinding(name, playwrightBinding)](#pageexposebindingname-playwrightbinding) for page-only version.
|
446 |
|
447 | An example of exposing page URL to all frames in all pages in the context:
|
448 | ```js
|
449 | const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
|
450 |
|
451 | (async () => {
|
452 | const browser = await webkit.launch({ headless: false });
|
453 | const context = await browser.newContext();
|
454 | await context.exposeBinding('pageURL', ({ page }) => page.url());
|
455 | const page = await context.newPage();
|
456 | await page.setContent(`
|
457 | <script>
|
458 | async function onClick() {
|
459 | document.querySelector('div').textContent = await window.pageURL();
|
460 | }
|
461 | </script>
|
462 | <button onclick="onClick()">Click me</button>
|
463 | <div></div>
|
464 | `);
|
465 | await page.click('button');
|
466 | })();
|
467 | ```
|
468 |
|
469 | #### browserContext.exposeFunction(name, playwrightFunction)
|
470 | - `name` <[string]> Name of the function on the window object.
|
471 | - `playwrightFunction` <[function]> Callback function that will be called in the Playwright's context.
|
472 | - returns: <[Promise]>
|
473 |
|
474 | The method adds a function called `name` on the `window` object of every frame in every page in the context.
|
475 | When called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of `playwrightFunction`.
|
476 |
|
477 | If the `playwrightFunction` returns a [Promise], it will be awaited.
|
478 |
|
479 | See [page.exposeFunction(name, playwrightFunction)](#pageexposefunctionname-playwrightfunction) for page-only version.
|
480 |
|
481 | An example of adding an `md5` function to all pages in the context:
|
482 | ```js
|
483 | const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
|
484 | const crypto = require('crypto');
|
485 |
|
486 | (async () => {
|
487 | const browser = await webkit.launch({ headless: false });
|
488 | const context = await browser.newContext();
|
489 | await context.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
|
490 | const page = await context.newPage();
|
491 | await page.setContent(`
|
492 | <script>
|
493 | async function onClick() {
|
494 | document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
|
495 | }
|
496 | </script>
|
497 | <button onclick="onClick()">Click me</button>
|
498 | <div></div>
|
499 | `);
|
500 | await page.click('button');
|
501 | })();
|
502 | ```
|
503 |
|
504 | #### browserContext.grantPermissions(permissions[][, options])
|
505 | - `permissions` <[Array]<[string]>> A permission or an array of permissions to grant. Permissions can be one of the following values:
|
506 | - `'*'`
|
507 | - `'geolocation'`
|
508 | - `'midi'`
|
509 | - `'midi-sysex'` (system-exclusive midi)
|
510 | - `'notifications'`
|
511 | - `'push'`
|
512 | - `'camera'`
|
513 | - `'microphone'`
|
514 | - `'background-sync'`
|
515 | - `'ambient-light-sensor'`
|
516 | - `'accelerometer'`
|
517 | - `'gyroscope'`
|
518 | - `'magnetometer'`
|
519 | - `'accessibility-events'`
|
520 | - `'clipboard-read'`
|
521 | - `'clipboard-write'`
|
522 | - `'payment-handler'`
|
523 | - `options` <[Object]>
|
524 | - `origin` <[string]> The [origin] to grant permissions to, e.g. "https://example.com".
|
525 | - returns: <[Promise]>
|
526 |
|
527 | Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
|
528 |
|
529 | #### browserContext.newPage()
|
530 | - returns: <[Promise]<[Page]>>
|
531 |
|
532 | Creates a new page in the browser context.
|
533 |
|
534 | #### browserContext.pages()
|
535 | - returns: <[Array]<[Page]>> All open pages in the context. Non visible pages, such as `"background_page"`, will not be listed here. You can find them using [chromiumBrowserContext.backgroundPages()](#chromiumbrowsercontextbackgroundpages).
|
536 |
|
537 | #### browserContext.route(url, handler)
|
538 | - `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
|
539 | - `handler` <[function]\([Route], [Request]\)> handler function to route the request.
|
540 | - returns: <[Promise]>
|
541 |
|
542 | Routing provides the capability to modify network requests that are made by any page in the browser context.
|
543 | Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
|
544 |
|
545 | An example of a naïve handler that aborts all image requests:
|
546 |
|
547 | ```js
|
548 | const context = await browser.newContext();
|
549 | await context.route('**/*.{png,jpg,jpeg}', route => route.abort());
|
550 | const page = await context.newPage();
|
551 | await page.goto('https://example.com');
|
552 | await browser.close();
|
553 | ```
|
554 |
|
555 | or the same snippet using a regex pattern instead:
|
556 |
|
557 | ```js
|
558 | const context = await browser.newContext();
|
559 | await context.route(/(\.png$)|(\.jpg$)/, route => route.abort());
|
560 | const page = await context.newPage();
|
561 | await page.goto('https://example.com');
|
562 | await browser.close();
|
563 | ```
|
564 |
|
565 | Page routes (set up with [page.route(url, handler)](#pagerouteurl-handler)) take precedence over browser context routes when request matches both handlers.
|
566 |
|
567 | > **NOTE** Enabling routing disables http cache.
|
568 |
|
569 | #### browserContext.setDefaultNavigationTimeout(timeout)
|
570 | - `timeout` <[number]> Maximum navigation time in milliseconds
|
571 |
|
572 | This setting will change the default maximum navigation time for the following methods and related shortcuts:
|
573 | - [page.goBack([options])](#pagegobackoptions)
|
574 | - [page.goForward([options])](#pagegoforwardoptions)
|
575 | - [page.goto(url[, options])](#pagegotourl-options)
|
576 | - [page.reload([options])](#pagereloadoptions)
|
577 | - [page.setContent(html[, options])](#pagesetcontenthtml-options)
|
578 | - [page.waitForNavigation([options])](#pagewaitfornavigationoptions)
|
579 |
|
580 | > **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) and [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) take priority over [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
|
581 |
|
582 | #### browserContext.setDefaultTimeout(timeout)
|
583 | - `timeout` <[number]> Maximum time in milliseconds
|
584 |
|
585 | This setting will change the default maximum time for all the methods accepting `timeout` option.
|
586 |
|
587 | > **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout), [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) and [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout) take priority over [`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout).
|
588 |
|
589 | #### browserContext.setExtraHTTPHeaders(headers)
|
590 | - `headers` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
|
591 | - returns: <[Promise]>
|
592 |
|
593 | 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()](#pagesetextrahttpheadersheaders). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.
|
594 |
|
595 | > **NOTE** `browserContext.setExtraHTTPHeaders` does not guarantee the order of headers in the outgoing requests.
|
596 |
|
597 | #### browserContext.setGeolocation(geolocation)
|
598 | - `geolocation` <?[Object]>
|
599 | - `latitude` <[number]> Latitude between -90 and 90. **required**
|
600 | - `longitude` <[number]> Longitude between -180 and 180. **required**
|
601 | - `accuracy` <[number]> Non-negative accuracy value. Defaults to `0`.
|
602 | - returns: <[Promise]>
|
603 |
|
604 | Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
|
605 |
|
606 | ```js
|
607 | await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
|
608 | ```
|
609 |
|
610 | > **NOTE** Consider using [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) to grant permissions for the browser context pages to read its geolocation.
|
611 |
|
612 | #### browserContext.setHTTPCredentials(httpCredentials)
|
613 | - `httpCredentials` <?[Object]>
|
614 | - `username` <[string]> **required**
|
615 | - `password` <[string]> **required**
|
616 | - returns: <[Promise]>
|
617 |
|
618 | Provide credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
|
619 |
|
620 | > **NOTE** Browsers may cache credentials that resulted in successful auth. That means passing different credentials after successful authentication or passing `null` to disable authentication is unreliable. Instead, create a separate browser context that will not have previous credentials cached.
|
621 |
|
622 | #### browserContext.setOffline(offline)
|
623 | - `offline` <[boolean]> Whether to emulate network being offline for the browser context.
|
624 | - returns: <[Promise]>
|
625 |
|
626 | #### browserContext.unroute(url[, handler])
|
627 | - `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with [browserContext.route(url, handler)](#browsercontextrouteurl-handler).
|
628 | - `handler` <[function]\([Route], [Request]\)> Handler function used to register a routing with [browserContext.route(url, handler)](#browsercontextrouteurl-handler).
|
629 | - returns: <[Promise]>
|
630 |
|
631 | Removes a route created with [browserContext.route(url, handler)](#browsercontextrouteurl-handler). When `handler` is not specified, removes all routes for the `url`.
|
632 |
|
633 | #### browserContext.waitForEvent(event[, optionsOrPredicate])
|
634 | - `event` <[string]> Event name, same one would pass into `browserContext.on(event)`.
|
635 | - `optionsOrPredicate` <[Function]|[Object]> Either a predicate that receives an event or an options object.
|
636 | - `predicate` <[Function]> receives the event data and resolves to truthy value when the waiting should resolve.
|
637 | - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout).
|
638 | - returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
|
639 |
|
640 | Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the context closes before the event
|
641 | is fired.
|
642 |
|
643 | ```js
|
644 | const context = await browser.newContext();
|
645 | await context.grantPermissions(['geolocation']);
|
646 | ```
|
647 |
|
648 | ### class: Page
|
649 |
|
650 | * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
|
651 |
|
652 | 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.
|
653 |
|
654 | This example creates a page, navigates it to a URL, and then saves a screenshot:
|
655 | ```js
|
656 | const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
|
657 |
|
658 | (async () => {
|
659 | const browser = await webkit.launch();
|
660 | const context = await browser.newContext();
|
661 | const page = await context.newPage();
|
662 | await page.goto('https://example.com');
|
663 | await page.screenshot({path: 'screenshot.png'});
|
664 | await browser.close();
|
665 | })();
|
666 | ```
|
667 |
|
668 | 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`.
|
669 |
|
670 | This example logs a message for a single page `load` event:
|
671 | ```js
|
672 | page.once('load', () => console.log('Page loaded!'));
|
673 | ```
|
674 |
|
675 | To unsubscribe from events use the `removeListener` method:
|
676 |
|
677 | ```js
|
678 | function logRequest(interceptedRequest) {
|
679 | console.log('A request was made:', interceptedRequest.url());
|
680 | }
|
681 | page.on('request', logRequest);
|
682 | // Sometime later...
|
683 | page.removeListener('request', logRequest);
|
684 | ```
|
685 |
|
686 |
|
687 | - [event: 'close'](#event-close-1)
|
688 | - [event: 'console'](#event-console)
|
689 | - [event: 'crash'](#event-crash)
|
690 | - [event: 'dialog'](#event-dialog)
|
691 | - [event: 'domcontentloaded'](#event-domcontentloaded)
|
692 | - [event: 'download'](#event-download)
|
693 | - [event: 'filechooser'](#event-filechooser)
|
694 | - [event: 'frameattached'](#event-frameattached)
|
695 | - [event: 'framedetached'](#event-framedetached)
|
696 | - [event: 'framenavigated'](#event-framenavigated)
|
697 | - [event: 'load'](#event-load)
|
698 | - [event: 'pageerror'](#event-pageerror)
|
699 | - [event: 'popup'](#event-popup)
|
700 | - [event: 'request'](#event-request)
|
701 | - [event: 'requestfailed'](#event-requestfailed)
|
702 | - [event: 'requestfinished'](#event-requestfinished)
|
703 | - [event: 'response'](#event-response)
|
704 | - [event: 'worker'](#event-worker)
|
705 | - [page.$(selector)](#pageselector)
|
706 | - [page.$$(selector)](#pageselector-1)
|
707 | - [page.$eval(selector, pageFunction[, arg])](#pageevalselector-pagefunction-arg)
|
708 | - [page.$$eval(selector, pageFunction[, arg])](#pageevalselector-pagefunction-arg-1)
|
709 | - [page.accessibility](#pageaccessibility)
|
710 | - [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg)
|
711 | - [page.addScriptTag(options)](#pageaddscripttagoptions)
|
712 | - [page.addStyleTag(options)](#pageaddstyletagoptions)
|
713 | - [page.bringToFront()](#pagebringtofront)
|
714 | - [page.check(selector, [options])](#pagecheckselector-options)
|
715 | - [page.click(selector[, options])](#pageclickselector-options)
|
716 | - [page.close([options])](#pagecloseoptions)
|
717 | - [page.content()](#pagecontent)
|
718 | - [page.context()](#pagecontext)
|
719 | - [page.coverage](#pagecoverage)
|
720 | - [page.dblclick(selector[, options])](#pagedblclickselector-options)
|
721 | - [page.dispatchEvent(selector, type[, eventInit, options])](#pagedispatcheventselector-type-eventinit-options)
|
722 | - [page.emulateMedia(options)](#pageemulatemediaoptions)
|
723 | - [page.evaluate(pageFunction[, arg])](#pageevaluatepagefunction-arg)
|
724 | - [page.evaluateHandle(pageFunction[, arg])](#pageevaluatehandlepagefunction-arg)
|
725 | - [page.exposeBinding(name, playwrightBinding)](#pageexposebindingname-playwrightbinding)
|
726 | - [page.exposeFunction(name, playwrightFunction)](#pageexposefunctionname-playwrightfunction)
|
727 | - [page.fill(selector, value[, options])](#pagefillselector-value-options)
|
728 | - [page.focus(selector[, options])](#pagefocusselector-options)
|
729 | - [page.frame(options)](#pageframeoptions)
|
730 | - [page.frames()](#pageframes)
|
731 | - [page.getAttribute(selector, name[, options])](#pagegetattributeselector-name-options)
|
732 | - [page.goBack([options])](#pagegobackoptions)
|
733 | - [page.goForward([options])](#pagegoforwardoptions)
|
734 | - [page.goto(url[, options])](#pagegotourl-options)
|
735 | - [page.hover(selector[, options])](#pagehoverselector-options)
|
736 | - [page.innerHTML(selector[, options])](#pageinnerhtmlselector-options)
|
737 | - [page.innerText(selector[, options])](#pageinnertextselector-options)
|
738 | - [page.isClosed()](#pageisclosed)
|
739 | - [page.keyboard](#pagekeyboard)
|
740 | - [page.mainFrame()](#pagemainframe)
|
741 | - [page.mouse](#pagemouse)
|
742 | - [page.opener()](#pageopener)
|
743 | - [page.pdf([options])](#pagepdfoptions)
|
744 | - [page.press(selector, key[, options])](#pagepressselector-key-options)
|
745 | - [page.reload([options])](#pagereloadoptions)
|
746 | - [page.route(url, handler)](#pagerouteurl-handler)
|
747 | - [page.screenshot([options])](#pagescreenshotoptions)
|
748 | - [page.selectOption(selector, values[, options])](#pageselectoptionselector-values-options)
|
749 | - [page.setContent(html[, options])](#pagesetcontenthtml-options)
|
750 | - [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout)
|
751 | - [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout)
|
752 | - [page.setExtraHTTPHeaders(headers)](#pagesetextrahttpheadersheaders)
|
753 | - [page.setInputFiles(selector, files[, options])](#pagesetinputfilesselector-files-options)
|
754 | - [page.setViewportSize(viewportSize)](#pagesetviewportsizeviewportsize)
|
755 | - [page.textContent(selector[, options])](#pagetextcontentselector-options)
|
756 | - [page.title()](#pagetitle)
|
757 | - [page.type(selector, text[, options])](#pagetypeselector-text-options)
|
758 | - [page.uncheck(selector, [options])](#pageuncheckselector-options)
|
759 | - [page.unroute(url[, handler])](#pageunrouteurl-handler)
|
760 | - [page.url()](#pageurl)
|
761 | - [page.viewportSize()](#pageviewportsize)
|
762 | - [page.waitForEvent(event[, optionsOrPredicate])](#pagewaitforeventevent-optionsorpredicate)
|
763 | - [page.waitForFunction(pageFunction[, arg, options])](#pagewaitforfunctionpagefunction-arg-options)
|
764 | - [page.waitForLoadState([state[, options]])](#pagewaitforloadstatestate-options)
|
765 | - [page.waitForNavigation([options])](#pagewaitfornavigationoptions)
|
766 | - [page.waitForRequest(urlOrPredicate[, options])](#pagewaitforrequesturlorpredicate-options)
|
767 | - [page.waitForResponse(urlOrPredicate[, options])](#pagewaitforresponseurlorpredicate-options)
|
768 | - [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options)
|
769 | - [page.waitForTimeout(timeout)](#pagewaitfortimeouttimeout)
|
770 | - [page.workers()](#pageworkers)
|
771 |
|
772 |
|
773 | #### event: 'close'
|
774 |
|
775 | Emitted when the page closes.
|
776 |
|
777 | #### event: 'console'
|
778 | - <[ConsoleMessage]>
|
779 |
|
780 | 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.
|
781 |
|
782 | The arguments passed into `console.log` appear as arguments on the event handler.
|
783 |
|
784 | An example of handling `console` event:
|
785 | ```js
|
786 | page.on('console', msg => {
|
787 | for (let i = 0; i < msg.args().length; ++i)
|
788 | console.log(`${i}: ${msg.args()[i]}`);
|
789 | });
|
790 | page.evaluate(() => console.log('hello', 5, {foo: 'bar'}));
|
791 | ```
|
792 |
|
793 | #### event: 'crash'
|
794 |
|
795 | 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.
|
796 |
|
797 | The most common way to deal with crashes is to catch an exception:
|
798 | ```js
|
799 | try {
|
800 | // Crash might happen during a click.
|
801 | await page.click('button');
|
802 | // Or while waiting for an event.
|
803 | await page.waitForEvent('popup');
|
804 | } catch (e) {
|
805 | // When the page crashes, exception message contains 'crash'.
|
806 | }
|
807 | ```
|
808 |
|
809 | However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, handling `crash` event helps:
|
810 |
|
811 | ```js
|
812 | await new Promise((resolve, reject) => {
|
813 | page.on('requestfinished', async request => {
|
814 | if (await someProcessing(request))
|
815 | resolve(request);
|
816 | });
|
817 | page.on('crash', error => reject(error));
|
818 | });
|
819 | ```
|
820 |
|
821 | #### event: 'dialog'
|
822 | - <[Dialog]>
|
823 |
|
824 | Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond to the dialog via [Dialog]'s [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods.
|
825 |
|
826 | #### event: 'domcontentloaded'
|
827 |
|
828 | Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
|
829 |
|
830 | #### event: 'download'
|
831 | - <[Download]>
|
832 |
|
833 | Emitted when attachment download started. User can access basic file operations on downloaded content via the passed [Download] instance.
|
834 |
|
835 | > **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.
|
836 |
|
837 | #### event: 'filechooser'
|
838 | - <[FileChooser]>
|
839 |
|
840 | Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can respond to it via setting the input files using [`fileChooser.setFiles`](#filechoosersetfilesfiles-options) that can be uploaded after that.
|
841 |
|
842 | ```js
|
843 | page.on('filechooser', async (fileChooser) => {
|
844 | await fileChooser.setFiles('/tmp/myfile.pdf');
|
845 | });
|
846 | ```
|
847 |
|
848 | #### event: 'frameattached'
|
849 | - <[Frame]>
|
850 |
|
851 | Emitted when a frame is attached.
|
852 |
|
853 | #### event: 'framedetached'
|
854 | - <[Frame]>
|
855 |
|
856 | Emitted when a frame is detached.
|
857 |
|
858 | #### event: 'framenavigated'
|
859 | - <[Frame]>
|
860 |
|
861 | Emitted when a frame is navigated to a new url.
|
862 |
|
863 | #### event: 'load'
|
864 |
|
865 | Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.
|
866 |
|
867 | #### event: 'pageerror'
|
868 | - <[Error]> The exception message
|
869 |
|
870 | Emitted when an uncaught exception happens within the page.
|
871 |
|
872 | #### event: 'popup'
|
873 | - <[Page]> Page corresponding to "popup" window
|
874 |
|
875 | Emitted when the page opens a new tab or window. This event is emitted in addition to the [`browserContext.on('page')`](#event-page), but only for popups relevant to this page.
|
876 |
|
877 | 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.
|
878 |
|
879 | ```js
|
880 | const [popup] = await Promise.all([
|
881 | page.waitForEvent('popup'),
|
882 | page.evaluate(() => window.open('https://example.com')),
|
883 | ]);
|
884 | console.log(await popup.evaluate('location.href'));
|
885 | ```
|
886 |
|
887 | > **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases).
|
888 |
|
889 | #### event: 'request'
|
890 | - <[Request]>
|
891 |
|
892 | Emitted when a page issues a request. The [request] object is read-only.
|
893 | In order to intercept and mutate requests, see [`page.route()`](#pagerouteurl-handler) or [`browserContext.route()`](#browsercontextrouteurl-handler).
|
894 |
|
895 | #### event: 'requestfailed'
|
896 | - <[Request]>
|
897 |
|
898 | Emitted when a request fails, for example by timing out.
|
899 |
|
900 | > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with [`'requestfinished'`](#event-requestfinished) event and not with [`'requestfailed'`](#event-requestfailed).
|
901 |
|
902 | #### event: 'requestfinished'
|
903 | - <[Request]>
|
904 |
|
905 | Emitted when a request finishes successfully.
|
906 |
|
907 | #### event: 'response'
|
908 | - <[Response]>
|
909 |
|
910 | Emitted when a [response] is received.
|
911 |
|
912 | #### event: 'worker'
|
913 | - <[Worker]>
|
914 |
|
915 | Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the page.
|
916 |
|
917 | #### page.$(selector)
|
918 | - `selector` <[string]> A selector to query page for. See [working with selectors](#working-with-selectors) for more details.
|
919 | - returns: <[Promise]<?[ElementHandle]>>
|
920 |
|
921 | The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to `null`.
|
922 |
|
923 | Shortcut for [page.mainFrame().$(selector)](#frameselector).
|
924 |
|
925 | #### page.$$(selector)
|
926 | - `selector` <[string]> A selector to query page for. See [working with selectors](#working-with-selectors) for more details.
|
927 | - returns: <[Promise]<[Array]<[ElementHandle]>>>
|
928 |
|
929 | The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to `[]`.
|
930 |
|
931 | Shortcut for [page.mainFrame().$$(selector)](#frameselector-1).
|
932 |
|
933 | #### page.$eval(selector, pageFunction[, arg])
|
934 | - `selector` <[string]> A selector to query page for. See [working with selectors](#working-with-selectors) for more details.
|
935 | - `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context
|
936 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
937 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
938 |
|
939 | 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.
|
940 |
|
941 | If `pageFunction` returns a [Promise], then `page.$eval` would wait for the promise to resolve and return its value.
|
942 |
|
943 | Examples:
|
944 | ```js
|
945 | const searchValue = await page.$eval('#search', el => el.value);
|
946 | const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
|
947 | const html = await page.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
|
948 | ```
|
949 |
|
950 | Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector-pagefunction-arg).
|
951 |
|
952 | #### page.$$eval(selector, pageFunction[, arg])
|
953 | - `selector` <[string]> A selector to query page for. See [working with selectors](#working-with-selectors) for more details.
|
954 | - `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context
|
955 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
956 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
957 |
|
958 | 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`.
|
959 |
|
960 | If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the promise to resolve and return its value.
|
961 |
|
962 | Examples:
|
963 | ```js
|
964 | const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);
|
965 | ```
|
966 |
|
967 | #### page.accessibility
|
968 | - returns: <[Accessibility]>
|
969 |
|
970 | #### page.addInitScript(script[, arg])
|
971 | - `script` <[function]|[string]|[Object]> Script to be evaluated in the page.
|
972 | - `path` <[string]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
973 | - `content` <[string]> Raw script content.
|
974 | - `arg` <[Serializable]> Optional argument to pass to `script` (only supported when passing a function).
|
975 | - returns: <[Promise]>
|
976 |
|
977 | Adds a script which would be evaluated in one of the following scenarios:
|
978 | - Whenever the page is navigated.
|
979 | - Whenever the child frame is attached or navigated. In this case, the scritp is evaluated in the context of the newly attached frame.
|
980 |
|
981 | 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`.
|
982 |
|
983 | An example of overriding `Math.random` before the page loads:
|
984 |
|
985 | ```js
|
986 | // preload.js
|
987 | Math.random = () => 42;
|
988 |
|
989 | // In your playwright script, assuming the preload.js file is in same folder
|
990 | const preloadFile = fs.readFileSync('./preload.js', 'utf8');
|
991 | await page.addInitScript(preloadFile);
|
992 | ```
|
993 |
|
994 | > **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is not defined.
|
995 |
|
996 | #### page.addScriptTag(options)
|
997 | - `options` <[Object]>
|
998 | - `url` <[string]> URL of a script to be added.
|
999 | - `path` <[string]> Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
1000 | - `content` <[string]> Raw JavaScript content to be injected into frame.
|
1001 | - `type` <[string]> Script type. Use 'module' in order to load a Javascript ES6 module. See [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
|
1002 | - returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the script's onload fires or when the script content was injected into frame.
|
1003 |
|
1004 | Adds a `<script>` tag into the page with the desired url or content.
|
1005 |
|
1006 | Shortcut for [page.mainFrame().addScriptTag(options)](#frameaddscripttagoptions).
|
1007 |
|
1008 | #### page.addStyleTag(options)
|
1009 | - `options` <[Object]>
|
1010 | - `url` <[string]> URL of the `<link>` tag.
|
1011 | - `path` <[string]> Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
1012 | - `content` <[string]> Raw CSS content to be injected into frame.
|
1013 | - returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
|
1014 |
|
1015 | Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
|
1016 |
|
1017 | Shortcut for [page.mainFrame().addStyleTag(options)](#frameaddstyletagoptions).
|
1018 |
|
1019 |
|
1020 | #### page.bringToFront()
|
1021 |
|
1022 | - returns: <[Promise]>
|
1023 |
|
1024 | Brings page to front (activates tab).
|
1025 |
|
1026 |
|
1027 | #### page.check(selector, [options])
|
1028 | - `selector` <[string]> A selector to search for checkbox or radio button to check. If there are multiple elements satisfying the selector, the first will be checked. See [working with selectors](#working-with-selectors) for more details.
|
1029 | - `options` <[Object]>
|
1030 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
1031 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1032 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1033 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully checked. The Promise will be rejected if there is no element matching `selector`.
|
1034 |
|
1035 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks. Then, if the element is not already checked, this method scrolls the element into view and uses [elementHandle.click](#elementhandleclickoptions) to click in the center of the element.
|
1036 |
|
1037 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
1038 |
|
1039 | Shortcut for [page.mainFrame().check(selector[, options])](#framecheckselector-options).
|
1040 |
|
1041 | #### page.click(selector[, options])
|
1042 | - `selector` <[string]> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked. See [working with selectors](#working-with-selectors) for more details.
|
1043 | - `options` <[Object]>
|
1044 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
1045 | - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
|
1046 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
1047 | - `position` <[Object]> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element.
|
1048 | - `x` <[number]>
|
1049 | - `y` <[number]>
|
1050 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
1051 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
1052 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1053 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1054 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully clicked. The Promise will be rejected if there is no element matching `selector`.
|
1055 |
|
1056 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to click in the center of the element.
|
1057 |
|
1058 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
1059 |
|
1060 |
|
1061 | Shortcut for [page.mainFrame().click(selector[, options])](#frameclickselector-options).
|
1062 |
|
1063 | #### page.close([options])
|
1064 | - `options` <[Object]>
|
1065 | - `runBeforeUnload` <[boolean]> Defaults to `false`. Whether to run the
|
1066 | [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload)
|
1067 | page handlers.
|
1068 | - returns: <[Promise]>
|
1069 |
|
1070 | By default, `page.close()` **does not** run beforeunload handlers.
|
1071 |
|
1072 | > **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned
|
1073 | > and should be handled manually via page's ['dialog'](#event-dialog) event.
|
1074 |
|
1075 | #### page.content()
|
1076 | - returns: <[Promise]<[string]>>
|
1077 |
|
1078 | Gets the full HTML contents of the page, including the doctype.
|
1079 |
|
1080 | #### page.context()
|
1081 |
|
1082 | - returns: <[BrowserContext]>
|
1083 |
|
1084 | Get the browser context that the page belongs to.
|
1085 |
|
1086 | #### page.coverage
|
1087 |
|
1088 | - returns: <?[ChromiumCoverage]>
|
1089 |
|
1090 | Browser-specific Coverage implementation, only available for Chromium atm. See [ChromiumCoverage](#class-chromiumcoverage) for more details.
|
1091 |
|
1092 | #### page.dblclick(selector[, options])
|
1093 | - `selector` <[string]> A selector to search for element to double click. If there are multiple elements satisfying the selector, the first will be double clicked. See [working with selectors](#working-with-selectors) for more details.
|
1094 | - `options` <[Object]>
|
1095 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
1096 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
1097 | - `position` <[Object]> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element.
|
1098 | - `x` <[number]>
|
1099 | - `y` <[number]>
|
1100 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
1101 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
1102 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1103 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1104 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully double clicked. The Promise will be rejected if there is no element matching `selector`.
|
1105 |
|
1106 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to double click in the center of the element.
|
1107 |
|
1108 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
1109 |
|
1110 | Bear in mind that if the first click of the `dblclick()` triggers a navigation event, there will be an exception.
|
1111 |
|
1112 | > **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
|
1113 |
|
1114 | Shortcut for [page.mainFrame().dblclick(selector[, options])](#framedblclickselector-options).
|
1115 |
|
1116 |
|
1117 | #### page.dispatchEvent(selector, type[, eventInit, options])
|
1118 | - `selector` <[string]> A selector to search for element to use. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
|
1119 | - `type` <[string]> DOM event type: `"click"`, `"dragstart"`, etc.
|
1120 | - `eventInit` <[Object]> event-specific initialization properties.
|
1121 | - `options` <[Object]>
|
1122 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1123 | - returns: <[Promise]>
|
1124 |
|
1125 | The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
|
1126 |
|
1127 | ```js
|
1128 | await page.dispatchEvent('button#submit', 'click');
|
1129 | ```
|
1130 |
|
1131 | 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.
|
1132 |
|
1133 | Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
|
1134 | - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
|
1135 | - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
|
1136 | - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
|
1137 | - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
|
1138 | - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
|
1139 | - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
|
1140 | - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
|
1141 |
|
1142 | You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
|
1143 |
|
1144 | ```js
|
1145 | // Note you can only create DataTransfer in Chromium and Firefox
|
1146 | const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
|
1147 | await page.dispatchEvent('#source', 'dragstart', { dataTransfer });
|
1148 | ```
|
1149 |
|
1150 | #### page.emulateMedia(options)
|
1151 | - `options` <[Object]>
|
1152 | - `media` <null|"screen"|"print"> Changes the CSS media type of the page. The only allowed values are `'screen'`, `'print'` and `null`. Passing `null` disables CSS media emulation. Omitting `media` or passing `undefined` does not change the emulated value.
|
1153 | - `colorScheme` <null|"light"|"dark"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. Passing `null` disables color scheme emulation. Omitting `colorScheme` or passing `undefined` does not change the emulated value.
|
1154 | - returns: <[Promise]>
|
1155 |
|
1156 | ```js
|
1157 | await page.evaluate(() => matchMedia('screen').matches);
|
1158 | // → true
|
1159 | await page.evaluate(() => matchMedia('print').matches);
|
1160 | // → false
|
1161 |
|
1162 | await page.emulateMedia({ media: 'print' });
|
1163 | await page.evaluate(() => matchMedia('screen').matches);
|
1164 | // → false
|
1165 | await page.evaluate(() => matchMedia('print').matches);
|
1166 | // → true
|
1167 |
|
1168 | await page.emulateMedia({});
|
1169 | await page.evaluate(() => matchMedia('screen').matches);
|
1170 | // → true
|
1171 | await page.evaluate(() => matchMedia('print').matches);
|
1172 | // → false
|
1173 | ```
|
1174 |
|
1175 | ```js
|
1176 | await page.emulateMedia({ colorScheme: 'dark' }] });
|
1177 | await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
|
1178 | // → true
|
1179 | await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
|
1180 | // → false
|
1181 | await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches);
|
1182 | // → false
|
1183 | ```
|
1184 |
|
1185 | #### page.evaluate(pageFunction[, arg])
|
1186 | - `pageFunction` <[function]|[string]> Function to be evaluated in the page context
|
1187 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
1188 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
1189 |
|
1190 | 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.
|
1191 |
|
1192 | 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.
|
1193 |
|
1194 | Passing argument to `pageFunction`:
|
1195 | ```js
|
1196 | const result = await page.evaluate(([x, y]) => {
|
1197 | return Promise.resolve(x * y);
|
1198 | }, [7, 8]);
|
1199 | console.log(result); // prints "56"
|
1200 | ```
|
1201 |
|
1202 | A string can also be passed in instead of a function:
|
1203 | ```js
|
1204 | console.log(await page.evaluate('1 + 2')); // prints "3"
|
1205 | const x = 10;
|
1206 | console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
|
1207 | ```
|
1208 |
|
1209 | [ElementHandle] instances can be passed as an argument to the `page.evaluate`:
|
1210 | ```js
|
1211 | const bodyHandle = await page.$('body');
|
1212 | const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
|
1213 | await bodyHandle.dispose();
|
1214 | ```
|
1215 |
|
1216 | Shortcut for [page.mainFrame().evaluate(pageFunction[, arg])](#frameevaluatepagefunction-arg).
|
1217 |
|
1218 | #### page.evaluateHandle(pageFunction[, arg])
|
1219 | - `pageFunction` <[function]|[string]> Function to be evaluated in the page context
|
1220 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
1221 | - returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
|
1222 |
|
1223 | The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page object (JSHandle).
|
1224 |
|
1225 | 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.
|
1226 |
|
1227 | A string can also be passed in instead of a function:
|
1228 | ```js
|
1229 | const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'
|
1230 | ```
|
1231 |
|
1232 | [JSHandle] instances can be passed as an argument to the `page.evaluateHandle`:
|
1233 | ```js
|
1234 | const aHandle = await page.evaluateHandle(() => document.body);
|
1235 | const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
|
1236 | console.log(await resultHandle.jsonValue());
|
1237 | await resultHandle.dispose();
|
1238 | ```
|
1239 |
|
1240 | #### page.exposeBinding(name, playwrightBinding)
|
1241 | - `name` <[string]> Name of the function on the window object.
|
1242 | - `playwrightBinding` <[function]> Callback function that will be called in the Playwright's context.
|
1243 | - returns: <[Promise]>
|
1244 |
|
1245 | The method adds a function called `name` on the `window` object of every frame in this page.
|
1246 | When called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of `playwrightBinding`.
|
1247 | If the `playwrightBinding` returns a [Promise], it will be awaited.
|
1248 |
|
1249 | The first argument of the `playwrightBinding` function contains information about the caller:
|
1250 | `{ browserContext: BrowserContext, page: Page, frame: Frame }`.
|
1251 |
|
1252 | See [browserContext.exposeBinding(name, playwrightBinding)](#browsercontextexposebindingname-playwrightbinding) for the context-wide version.
|
1253 |
|
1254 | > **NOTE** Functions installed via `page.exposeBinding` survive navigations.
|
1255 |
|
1256 | An example of exposing page URL to all frames in a page:
|
1257 | ```js
|
1258 | const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
|
1259 |
|
1260 | (async () => {
|
1261 | const browser = await webkit.launch({ headless: false });
|
1262 | const context = await browser.newContext();
|
1263 | const page = await context.newPage();
|
1264 | await page.exposeBinding('pageURL', ({ page }) => page.url());
|
1265 | await page.setContent(`
|
1266 | <script>
|
1267 | async function onClick() {
|
1268 | document.querySelector('div').textContent = await window.pageURL();
|
1269 | }
|
1270 | </script>
|
1271 | <button onclick="onClick()">Click me</button>
|
1272 | <div></div>
|
1273 | `);
|
1274 | await page.click('button');
|
1275 | })();
|
1276 | ```
|
1277 |
|
1278 | #### page.exposeFunction(name, playwrightFunction)
|
1279 | - `name` <[string]> Name of the function on the window object
|
1280 | - `playwrightFunction` <[function]> Callback function which will be called in Playwright's context.
|
1281 | - returns: <[Promise]>
|
1282 |
|
1283 | The method adds a function called `name` on the `window` object of every frame in the page.
|
1284 | When called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of `playwrightFunction`.
|
1285 |
|
1286 | If the `playwrightFunction` returns a [Promise], it will be awaited.
|
1287 |
|
1288 | See [browserContext.exposeFunction(name, playwrightFunction)](#browsercontextexposefunctionname-playwrightfunction) for context-wide exposed function.
|
1289 |
|
1290 | > **NOTE** Functions installed via `page.exposeFunction` survive navigations.
|
1291 |
|
1292 | An example of adding an `md5` function to the page:
|
1293 | ```js
|
1294 | const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
|
1295 | const crypto = require('crypto');
|
1296 |
|
1297 | (async () => {
|
1298 | const browser = await webkit.launch({ headless: false });
|
1299 | const page = await browser.newPage();
|
1300 | await page.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
|
1301 | await page.setContent(`
|
1302 | <script>
|
1303 | async function onClick() {
|
1304 | document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
|
1305 | }
|
1306 | </script>
|
1307 | <button onclick="onClick()">Click me</button>
|
1308 | <div></div>
|
1309 | `);
|
1310 | await page.click('button');
|
1311 | })();
|
1312 | ```
|
1313 |
|
1314 | An example of adding a `window.readfile` function to the page:
|
1315 |
|
1316 | ```js
|
1317 | const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
|
1318 | const fs = require('fs');
|
1319 |
|
1320 | (async () => {
|
1321 | const browser = await chromium.launch();
|
1322 | const page = await browser.newPage();
|
1323 | page.on('console', msg => console.log(msg.text()));
|
1324 | await page.exposeFunction('readfile', async filePath => {
|
1325 | return new Promise((resolve, reject) => {
|
1326 | fs.readFile(filePath, 'utf8', (err, text) => {
|
1327 | if (err)
|
1328 | reject(err);
|
1329 | else
|
1330 | resolve(text);
|
1331 | });
|
1332 | });
|
1333 | });
|
1334 | await page.evaluate(async () => {
|
1335 | // use window.readfile to read contents of a file
|
1336 | const content = await window.readfile('/etc/hosts');
|
1337 | console.log(content);
|
1338 | });
|
1339 | await browser.close();
|
1340 | })();
|
1341 | ```
|
1342 |
|
1343 | #### page.fill(selector, value[, options])
|
1344 | - `selector` <[string]> A selector to query page for. See [working with selectors](#working-with-selectors) for more details.
|
1345 | - `value` <[string]> Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
|
1346 | - `options` <[Object]>
|
1347 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1348 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1349 | - returns: <[Promise]>
|
1350 |
|
1351 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
|
1352 | If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
|
1353 | Note that you can pass an empty string to clear the input field.
|
1354 |
|
1355 | To send fine-grained keyboard events, use [`page.type`](#pagetypeselector-text-options).
|
1356 |
|
1357 | Shortcut for [page.mainFrame().fill()](#framefillselector-value-options)
|
1358 |
|
1359 | #### page.focus(selector[, options])
|
1360 | - `selector` <[string]> A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused. See [working with selectors](#working-with-selectors) for more details.
|
1361 | - `options` <[Object]>
|
1362 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1363 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.
|
1364 |
|
1365 | This method fetches an element with `selector` and focuses it.
|
1366 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
|
1367 |
|
1368 | Shortcut for [page.mainFrame().focus(selector)](#framefocusselector-options).
|
1369 |
|
1370 | #### page.frame(options)
|
1371 | - `options` <[string]|[Object]> Frame name or other frame lookup options.
|
1372 | - `name` <[string]> frame name specified in the `iframe`'s `name` attribute
|
1373 | - `url` <[string]|[RegExp]|[Function]> A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] object.
|
1374 | - returns: <?[Frame]> frame matching the criteria. Returns `null` if no frame matches.
|
1375 |
|
1376 | ```js
|
1377 | const frame = page.frame('frame-name');
|
1378 | ```
|
1379 |
|
1380 | ```js
|
1381 | const frame = page.frame({ url: /.*domain.*/ });
|
1382 | ```
|
1383 |
|
1384 | Returns frame matching the specified criteria. Either `name` or `url` must be specified.
|
1385 |
|
1386 | #### page.frames()
|
1387 | - returns: <[Array]<[Frame]>> An array of all frames attached to the page.
|
1388 |
|
1389 | #### page.getAttribute(selector, name[, options])
|
1390 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
1391 | - `name` <[string]> Attribute name to get the value for.
|
1392 | - `options` <[Object]>
|
1393 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1394 | - returns: <[Promise]<null|[string]>>
|
1395 |
|
1396 | Returns element attribute value.
|
1397 |
|
1398 | #### page.goBack([options])
|
1399 | - `options` <[Object]> Navigation parameters which might have the following properties:
|
1400 | - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1401 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
1402 | - `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
|
1403 | - `'load'` - consider navigation to be finished when the `load` event is fired.
|
1404 | - `'networkidle'` - consider navigation to be finished when there are no network connections for at least `500` ms.
|
1405 | - returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
|
1406 | can not go back, resolves to `null`.
|
1407 |
|
1408 | Navigate to the previous page in history.
|
1409 |
|
1410 | #### page.goForward([options])
|
1411 | - `options` <[Object]> Navigation parameters which might have the following properties:
|
1412 | - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1413 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
1414 | - `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
|
1415 | - `'load'` - consider navigation to be finished when the `load` event is fired.
|
1416 | - `'networkidle'` - consider navigation to be finished when there are no network connections for at least `500` ms.
|
1417 | - returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
|
1418 | can not go forward, resolves to `null`.
|
1419 |
|
1420 | Navigate to the next page in history.
|
1421 |
|
1422 | #### page.goto(url[, options])
|
1423 | - `url` <[string]> URL to navigate page to. The url should include scheme, e.g. `https://`.
|
1424 | - `options` <[Object]> Navigation parameters which might have the following properties:
|
1425 | - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1426 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
1427 | - `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
|
1428 | - `'load'` - consider navigation to be finished when the `load` event is fired.
|
1429 | - `'networkidle'` - consider navigation to be finished when there are no network connections for at least `500` ms.
|
1430 | - `referer` <[string]> Referer header value. If provided it will take preference over the referer header value set by [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders).
|
1431 | - returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
|
1432 |
|
1433 | `page.goto` will throw an error if:
|
1434 | - there's an SSL error (e.g. in case of self-signed certificates).
|
1435 | - target URL is invalid.
|
1436 | - the `timeout` is exceeded during navigation.
|
1437 | - the remote server does not respond or is unreachable.
|
1438 | - the main resource failed to load.
|
1439 |
|
1440 | `page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).
|
1441 |
|
1442 | > **NOTE** `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
|
1443 |
|
1444 | > **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
|
1445 |
|
1446 | Shortcut for [page.mainFrame().goto(url[, options])](#framegotourl-options)
|
1447 |
|
1448 | #### page.hover(selector[, options])
|
1449 | - `selector` <[string]> A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered. See [working with selectors](#working-with-selectors) for more details.
|
1450 | - `options` <[Object]>
|
1451 | - `position` <[Object]> A point to hover relative to the top-left corner of element padding box. If not specified, hovers over some visible point of the element.
|
1452 | - `x` <[number]>
|
1453 | - `y` <[number]>
|
1454 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
1455 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
1456 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1457 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully hovered. Promise gets rejected if there's no element matching `selector`.
|
1458 |
|
1459 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to hover over the center of the element.
|
1460 |
|
1461 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
1462 |
|
1463 | Shortcut for [page.mainFrame().hover(selector[, options])](#framehoverselector-options).
|
1464 |
|
1465 | #### page.innerHTML(selector[, options])
|
1466 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
1467 | - `options` <[Object]>
|
1468 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1469 | - returns: <[Promise]<[string]>>
|
1470 |
|
1471 | Resolves to the `element.innerHTML`.
|
1472 |
|
1473 | #### page.innerText(selector[, options])
|
1474 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
1475 | - `options` <[Object]>
|
1476 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1477 | - returns: <[Promise]<[string]>>
|
1478 |
|
1479 | Resolves to the `element.innerText`.
|
1480 |
|
1481 | #### page.isClosed()
|
1482 |
|
1483 | - returns: <[boolean]>
|
1484 |
|
1485 | Indicates that the page has been closed.
|
1486 |
|
1487 | #### page.keyboard
|
1488 |
|
1489 | - returns: <[Keyboard]>
|
1490 |
|
1491 | #### page.mainFrame()
|
1492 | - returns: <[Frame]> The page's main frame.
|
1493 |
|
1494 | Page is guaranteed to have a main frame which persists during navigations.
|
1495 |
|
1496 | #### page.mouse
|
1497 |
|
1498 | - returns: <[Mouse]>
|
1499 |
|
1500 | #### page.opener()
|
1501 |
|
1502 | - returns: <[Promise]<?[Page]>> Promise which resolves to the opener for popup pages and `null` for others. If the opener has been closed already the promise may resolve to `null`.
|
1503 |
|
1504 | #### page.pdf([options])
|
1505 | - `options` <[Object]> Options object which might have the following properties:
|
1506 | - `path` <[string]> The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the PDF won't be saved to the disk.
|
1507 | - `scale` <[number]> Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.
|
1508 | - `displayHeaderFooter` <[boolean]> Display header and footer. Defaults to `false`.
|
1509 | - `headerTemplate` <[string]> HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them:
|
1510 | - `'date'` formatted print date
|
1511 | - `'title'` document title
|
1512 | - `'url'` document location
|
1513 | - `'pageNumber'` current page number
|
1514 | - `'totalPages'` total pages in the document
|
1515 | - `footerTemplate` <[string]> HTML template for the print footer. Should use the same format as the `headerTemplate`.
|
1516 | - `printBackground` <[boolean]> Print background graphics. Defaults to `false`.
|
1517 | - `landscape` <[boolean]> Paper orientation. Defaults to `false`.
|
1518 | - `pageRanges` <[string]> Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
|
1519 | - `format` <[string]> Paper format. If set, takes priority over `width` or `height` options. Defaults to 'Letter'.
|
1520 | - `width` <[string]|[number]> Paper width, accepts values labeled with units.
|
1521 | - `height` <[string]|[number]> Paper height, accepts values labeled with units.
|
1522 | - `margin` <[Object]> Paper margins, defaults to none.
|
1523 | - `top` <[string]|[number]> Top margin, accepts values labeled with units. Defaults to `0`.
|
1524 | - `right` <[string]|[number]> Right margin, accepts values labeled with units. Defaults to `0`.
|
1525 | - `bottom` <[string]|[number]> Bottom margin, accepts values labeled with units. Defaults to `0`.
|
1526 | - `left` <[string]|[number]> Left margin, accepts values labeled with units. Defaults to `0`.
|
1527 | - `preferCSSPageSize` <[boolean]> Give any CSS `@page` size declared in the page priority over what is declared in `width` and `height` or `format` options. Defaults to `false`, which will scale the content to fit the paper size.
|
1528 | - returns: <[Promise]<[Buffer]>> Promise which resolves with PDF buffer.
|
1529 |
|
1530 | > **NOTE** Generating a pdf is currently only supported in Chromium headless.
|
1531 |
|
1532 | `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call [page.emulateMedia({ media: 'screen' })](#pageemulatemediaoptions) before calling `page.pdf()`:
|
1533 |
|
1534 | > **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to force rendering of exact colors.
|
1535 |
|
1536 | ```js
|
1537 | // Generates a PDF with 'screen' media type.
|
1538 | await page.emulateMedia({media: 'screen'});
|
1539 | await page.pdf({path: 'page.pdf'});
|
1540 | ```
|
1541 |
|
1542 | The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as pixels.
|
1543 |
|
1544 | A few examples:
|
1545 | - `page.pdf({width: 100})` - prints with width set to 100 pixels
|
1546 | - `page.pdf({width: '100px'})` - prints with width set to 100 pixels
|
1547 | - `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
|
1548 |
|
1549 | All possible units are:
|
1550 | - `px` - pixel
|
1551 | - `in` - inch
|
1552 | - `cm` - centimeter
|
1553 | - `mm` - millimeter
|
1554 |
|
1555 | The `format` options are:
|
1556 | - `Letter`: 8.5in x 11in
|
1557 | - `Legal`: 8.5in x 14in
|
1558 | - `Tabloid`: 11in x 17in
|
1559 | - `Ledger`: 17in x 11in
|
1560 | - `A0`: 33.1in x 46.8in
|
1561 | - `A1`: 23.4in x 33.1in
|
1562 | - `A2`: 16.54in x 23.4in
|
1563 | - `A3`: 11.7in x 16.54in
|
1564 | - `A4`: 8.27in x 11.7in
|
1565 | - `A5`: 5.83in x 8.27in
|
1566 | - `A6`: 4.13in x 5.83in
|
1567 |
|
1568 | > **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations:
|
1569 | > 1. Script tags inside templates are not evaluated.
|
1570 | > 2. Page styles are not visible inside templates.
|
1571 |
|
1572 | #### page.press(selector, key[, options])
|
1573 | - `selector` <[string]> A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
|
1574 | - `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
|
1575 | - `options` <[Object]>
|
1576 | - `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
|
1577 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1578 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1579 | - returns: <[Promise]>
|
1580 |
|
1581 | Focuses the element, and then uses [`keyboard.down`](#keyboarddownkey) and [`keyboard.up`](#keyboardupkey).
|
1582 |
|
1583 | `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
|
1584 |
|
1585 | `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
|
1586 |
|
1587 | Following modification shortcuts are also suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
|
1588 |
|
1589 | Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
|
1590 |
|
1591 | If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
|
1592 |
|
1593 | Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
|
1594 |
|
1595 | ```js
|
1596 | const page = await browser.newPage();
|
1597 | await page.goto('https://keycode.info');
|
1598 | await page.press('body', 'A');
|
1599 | await page.screenshot({ path: 'A.png' });
|
1600 | await page.press('body', 'ArrowLeft');
|
1601 | await page.screenshot({ path: 'ArrowLeft.png' });
|
1602 | await page.press('body', 'Shift+O');
|
1603 | await page.screenshot({ path: 'O.png' });
|
1604 | await browser.close();
|
1605 | ```
|
1606 |
|
1607 | #### page.reload([options])
|
1608 | - `options` <[Object]> Navigation parameters which might have the following properties:
|
1609 | - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1610 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
1611 | - `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
|
1612 | - `'load'` - consider navigation to be finished when the `load` event is fired.
|
1613 | - `'networkidle'` - consider navigation to be finished when there are no network connections for at least `500` ms.
|
1614 | - returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
|
1615 |
|
1616 | #### page.route(url, handler)
|
1617 | - `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
|
1618 | - `handler` <[function]\([Route], [Request]\)> handler function to route the request.
|
1619 | - returns: <[Promise]>.
|
1620 |
|
1621 | Routing provides the capability to modify network requests that are made by a page.
|
1622 |
|
1623 | Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
|
1624 |
|
1625 | An example of a naïve handler that aborts all image requests:
|
1626 |
|
1627 | ```js
|
1628 | const page = await browser.newPage();
|
1629 | await page.route('**/*.{png,jpg,jpeg}', route => route.abort());
|
1630 | await page.goto('https://example.com');
|
1631 | await browser.close();
|
1632 | ```
|
1633 |
|
1634 | or the same snippet using a regex pattern instead:
|
1635 |
|
1636 | ```js
|
1637 | const page = await browser.newPage();
|
1638 | await page.route(/(\.png$)|(\.jpg$)/, route => route.abort());
|
1639 | await page.goto('https://example.com');
|
1640 | await browser.close();
|
1641 | ```
|
1642 |
|
1643 | Page routes take precedence over browser context routes (set up with [browserContext.route(url, handler)](#browsercontextrouteurl-handler)) when request matches both handlers.
|
1644 |
|
1645 | > **NOTE** Enabling routing disables http cache.
|
1646 |
|
1647 | #### page.screenshot([options])
|
1648 | - `options` <[Object]> Options object which might have the following properties:
|
1649 | - `path` <[string]> The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.
|
1650 | - `type` <"png"|"jpeg"> Specify screenshot type, defaults to `png`.
|
1651 | - `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.
|
1652 | - `fullPage` <[boolean]> When true, takes a screenshot of the full scrollable page, instead of the currently visibvle viewport. Defaults to `false`.
|
1653 | - `clip` <[Object]> An object which specifies clipping of the resulting image. Should have the following fields:
|
1654 | - `x` <[number]> x-coordinate of top-left corner of clip area
|
1655 | - `y` <[number]> y-coordinate of top-left corner of clip area
|
1656 | - `width` <[number]> width of clipping area
|
1657 | - `height` <[number]> height of clipping area
|
1658 | - `omitBackground` <[boolean]> Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images. Defaults to `false`.
|
1659 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1660 | - returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with the captured screenshot.
|
1661 |
|
1662 | > **NOTE** Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See https://crbug.com/741689 for discussion.
|
1663 |
|
1664 | #### page.selectOption(selector, values[, options])
|
1665 | - `selector` <[string]> A selector to query page for. See [working with selectors](#working-with-selectors) for more details.
|
1666 | - `values` <null|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.
|
1667 | - `value` <[string]> Matches by `option.value`.
|
1668 | - `label` <[string]> Matches by `option.label`.
|
1669 | - `index` <[number]> Matches by the index.
|
1670 | - `options` <[Object]>
|
1671 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1672 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1673 | - returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
|
1674 |
|
1675 | Triggers a `change` and `input` event once all the provided options have been selected.
|
1676 | If there's no `<select>` element matching `selector`, the method throws an error.
|
1677 |
|
1678 | ```js
|
1679 | // single selection matching the value
|
1680 | page.selectOption('select#colors', 'blue');
|
1681 |
|
1682 | // single selection matching both the value and the label
|
1683 | page.selectOption('select#colors', { label: 'Blue' });
|
1684 |
|
1685 | // multiple selection
|
1686 | page.selectOption('select#colors', ['red', 'green', 'blue']);
|
1687 |
|
1688 | ```
|
1689 |
|
1690 | Shortcut for [page.mainFrame().selectOption()](#frameselectoptionselector-values-options)
|
1691 |
|
1692 | #### page.setContent(html[, options])
|
1693 | - `html` <[string]> HTML markup to assign to the page.
|
1694 | - `options` <[Object]> Parameters which might have the following properties:
|
1695 | - `timeout` <[number]> Maximum time in milliseconds for resources to load, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1696 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider setting markup succeeded, defaults to `load`. Given an array of event strings, setting content is considered to be successful after all events have been fired. Events can be either:
|
1697 | - `'load'` - consider setting content to be finished when the `load` event is fired.
|
1698 | - `'domcontentloaded'` - consider setting content to be finished when the `DOMContentLoaded` event is fired.
|
1699 | - `'networkidle'` - consider setting content to be finished when there are no network connections for at least `500` ms.
|
1700 | - returns: <[Promise]>
|
1701 |
|
1702 | #### page.setDefaultNavigationTimeout(timeout)
|
1703 | - `timeout` <[number]> Maximum navigation time in milliseconds
|
1704 |
|
1705 | This setting will change the default maximum navigation time for the following methods and related shortcuts:
|
1706 | - [page.goBack([options])](#pagegobackoptions)
|
1707 | - [page.goForward([options])](#pagegoforwardoptions)
|
1708 | - [page.goto(url[, options])](#pagegotourl-options)
|
1709 | - [page.reload([options])](#pagereloadoptions)
|
1710 | - [page.setContent(html[, options])](#pagesetcontenthtml-options)
|
1711 | - [page.waitForNavigation([options])](#pagewaitfornavigationoptions)
|
1712 |
|
1713 | > **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout), [`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout) and [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
|
1714 |
|
1715 |
|
1716 | #### page.setDefaultTimeout(timeout)
|
1717 | - `timeout` <[number]> Maximum time in milliseconds
|
1718 |
|
1719 | This setting will change the default maximum time for all the methods accepting `timeout` option.
|
1720 |
|
1721 | > **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout).
|
1722 |
|
1723 | #### page.setExtraHTTPHeaders(headers)
|
1724 | - `headers` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
|
1725 | - returns: <[Promise]>
|
1726 |
|
1727 | The extra HTTP headers will be sent with every request the page initiates.
|
1728 |
|
1729 | > **NOTE** page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
|
1730 |
|
1731 | #### page.setInputFiles(selector, files[, options])
|
1732 | - `selector` <[string]> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked. See [working with selectors](#working-with-selectors) for more details.
|
1733 | - `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
|
1734 | - `name` <[string]> [File] name **required**
|
1735 | - `mimeType` <[string]> [File] type **required**
|
1736 | - `buffer` <[Buffer]> File content **required**
|
1737 | - `options` <[Object]>
|
1738 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1739 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1740 | - returns: <[Promise]>
|
1741 |
|
1742 | This method expects `selector` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
|
1743 |
|
1744 | Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
|
1745 |
|
1746 |
|
1747 | #### page.setViewportSize(viewportSize)
|
1748 | - `viewportSize` <[Object]>
|
1749 | - `width` <[number]> page width in pixels. **required**
|
1750 | - `height` <[number]> page height in pixels. **required**
|
1751 | - returns: <[Promise]>
|
1752 |
|
1753 | In the case of multiple pages in a single browser, each page can have its own viewport size. However, [browser.newContext([options])](#browsernewcontextoptions) allows to set viewport size (and more) for all pages in the context at once.
|
1754 |
|
1755 | `page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page.
|
1756 |
|
1757 | ```js
|
1758 | const page = await browser.newPage();
|
1759 | await page.setViewportSize({
|
1760 | width: 640,
|
1761 | height: 480,
|
1762 | });
|
1763 | await page.goto('https://example.com');
|
1764 | ```
|
1765 |
|
1766 | #### page.textContent(selector[, options])
|
1767 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
1768 | - `options` <[Object]>
|
1769 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1770 | - returns: <[Promise]<null|[string]>>
|
1771 |
|
1772 | Resolves to the `element.textContent`.
|
1773 |
|
1774 |
|
1775 | #### page.title()
|
1776 | - returns: <[Promise]<[string]>> The page's title.
|
1777 |
|
1778 | Shortcut for [page.mainFrame().title()](#frametitle).
|
1779 |
|
1780 |
|
1781 |
|
1782 | #### page.type(selector, text[, options])
|
1783 | - `selector` <[string]> A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
|
1784 | - `text` <[string]> A text to type into a focused element.
|
1785 | - `options` <[Object]>
|
1786 | - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.
|
1787 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1788 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1789 | - returns: <[Promise]>
|
1790 |
|
1791 | Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [`page.fill`](#pagefillselector-value-options).
|
1792 |
|
1793 | To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).
|
1794 |
|
1795 | ```js
|
1796 | await page.type('#mytextarea', 'Hello'); // Types instantly
|
1797 | await page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
|
1798 | ```
|
1799 |
|
1800 | Shortcut for [page.mainFrame().type(selector, text[, options])](#frametypeselector-text-options).
|
1801 |
|
1802 | #### page.uncheck(selector, [options])
|
1803 | - `selector` <[string]> A selector to search for uncheckbox to check. If there are multiple elements satisfying the selector, the first will be checked. See [working with selectors](#working-with-selectors) for more details.
|
1804 | - `options` <[Object]>
|
1805 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
1806 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
1807 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1808 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully unchecked. The Promise will be rejected if there is no element matching `selector`.
|
1809 |
|
1810 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks. Then, if the element is not already unchecked, this method scrolls the element into view and uses [elementHandle.click](#elementhandleclickoptions) to click in the center of the element.
|
1811 |
|
1812 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
1813 |
|
1814 | Shortcut for [page.mainFrame().uncheck(selector[, options])](#frameuncheckselector-options).
|
1815 |
|
1816 | #### page.unroute(url[, handler])
|
1817 | - `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
|
1818 | - `handler` <[function]\([Route], [Request]\)> Handler function to route the request.
|
1819 | - returns: <[Promise]>
|
1820 |
|
1821 | Removes a route created with [page.route(url, handler)](#pagerouteurl-handler). When `handler` is not specified, removes all routes for the `url`.
|
1822 |
|
1823 | #### page.url()
|
1824 | - returns: <[string]>
|
1825 |
|
1826 | This is a shortcut for [page.mainFrame().url()](#frameurl)
|
1827 |
|
1828 | #### page.viewportSize()
|
1829 | - returns: <?[Object]>
|
1830 | - `width` <[number]> page width in pixels.
|
1831 | - `height` <[number]> page height in pixels.
|
1832 |
|
1833 | #### page.waitForEvent(event[, optionsOrPredicate])
|
1834 | - `event` <[string]> Event name, same one would pass into `page.on(event)`.
|
1835 | - `optionsOrPredicate` <[Function]|[Object]> Either a predicate that receives an event or an options object.
|
1836 | - `predicate` <[Function]> receives the event data and resolves to truthy value when the waiting should resolve.
|
1837 | - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1838 | - returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
|
1839 |
|
1840 | Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the page is closed before the event
|
1841 | is fired.
|
1842 |
|
1843 | #### page.waitForFunction(pageFunction[, arg, options])
|
1844 | - `pageFunction` <[function]|[string]> Function to be evaluated in browser context
|
1845 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
1846 | - `options` <[Object]> Optional waiting parameters
|
1847 | - `polling` <[number]|"raf"> If `polling` is `'raf'`, then `pageFunction` is constantly executed in `requestAnimationFrame` callback. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to `raf`.
|
1848 | - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.
|
1849 | - returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
|
1850 |
|
1851 | The `waitForFunction` can be used to observe viewport size change:
|
1852 | ```js
|
1853 | const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
|
1854 |
|
1855 | (async () => {
|
1856 | const browser = await webkit.launch();
|
1857 | const page = await browser.newPage();
|
1858 | const watchDog = page.waitForFunction('window.innerWidth < 100');
|
1859 | await page.setViewportSize({width: 50, height: 50});
|
1860 | await watchDog;
|
1861 | await browser.close();
|
1862 | })();
|
1863 | ```
|
1864 |
|
1865 | To pass an argument from Node.js to the predicate of `page.waitForFunction` function:
|
1866 |
|
1867 | ```js
|
1868 | const selector = '.foo';
|
1869 | await page.waitForFunction(selector => !!document.querySelector(selector), selector);
|
1870 | ```
|
1871 |
|
1872 | Shortcut for [page.mainFrame().waitForFunction(pageFunction, arg, options]])](#framewaitforfunctionpagefunction-arg-options).
|
1873 |
|
1874 | #### page.waitForLoadState([state[, options]])
|
1875 | - `state` <"load"|"domcontentloaded"|"networkidle"> Load state to wait for, defaults to `load`. If the state has been already reached while loading current document, the method resolves immediately.
|
1876 | - `'load'` - wait for the `load` event to be fired.
|
1877 | - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
|
1878 | - `'networkidle'` - wait until there are no network connections for at least `500` ms.
|
1879 | - `options` <[Object]>
|
1880 | - `timeout` <[number]> Maximum waiting time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1881 | - returns: <[Promise]> Promise which resolves when the required load state has been reached.
|
1882 |
|
1883 | This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
|
1884 |
|
1885 | ```js
|
1886 | await page.click('button'); // Click triggers navigation.
|
1887 | await page.waitForLoadState(); // The promise resolves after 'load' event.
|
1888 | ```
|
1889 |
|
1890 | ```js
|
1891 | const [popup] = await Promise.all([
|
1892 | page.waitForEvent('popup'),
|
1893 | page.click('button'), // Click triggers a popup.
|
1894 | ])
|
1895 | await popup.waitForLoadState('domcontentloaded'); // The promise resolves after 'domcontentloaded' event.
|
1896 | console.log(await popup.title()); // Popup is ready to use.
|
1897 | ```
|
1898 |
|
1899 | Shortcut for [page.mainFrame().waitForLoadState([options])](#framewaitforloadstatestate-options).
|
1900 |
|
1901 | #### page.waitForNavigation([options])
|
1902 | - `options` <[Object]> Navigation parameters which might have the following properties:
|
1903 | - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1904 | - `url` <[string]|[RegExp]|[Function]> A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.
|
1905 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
1906 | - `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
|
1907 | - `'load'` - consider navigation to be finished when the `load` event is fired.
|
1908 | - `'networkidle'` - consider navigation to be finished when there are no network connections for at least `500` ms.
|
1909 | - returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
|
1910 |
|
1911 | This resolves when the page navigates to a new URL or reloads. It is useful for when you run code
|
1912 | which will indirectly cause the page to navigate. Consider this example:
|
1913 |
|
1914 | ```js
|
1915 | const [response] = await Promise.all([
|
1916 | page.waitForNavigation(), // The promise resolves after navigation has finished
|
1917 | page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
|
1918 | ]);
|
1919 | ```
|
1920 |
|
1921 | **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
|
1922 |
|
1923 | Shortcut for [page.mainFrame().waitForNavigation(options)](#framewaitfornavigationoptions).
|
1924 |
|
1925 | #### page.waitForRequest(urlOrPredicate[, options])
|
1926 | - `urlOrPredicate` <[string]|[RegExp]|[Function]> Request URL string, regex or predicate receiving [Request] object.
|
1927 | - `options` <[Object]> Optional waiting parameters
|
1928 | - `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.
|
1929 | - returns: <[Promise]<[Request]>> Promise which resolves to the matched request.
|
1930 |
|
1931 | ```js
|
1932 | const firstRequest = await page.waitForRequest('http://example.com/resource');
|
1933 | const finalRequest = await page.waitForRequest(request => request.url() === 'http://example.com' && request.method() === 'GET');
|
1934 | return firstRequest.url();
|
1935 | ```
|
1936 |
|
1937 | ```js
|
1938 | await page.waitForRequest(request => request.url().searchParams.get('foo') === 'bar' && request.url().searchParams.get('foo2') === 'bar2');
|
1939 | ```
|
1940 |
|
1941 | #### page.waitForResponse(urlOrPredicate[, options])
|
1942 | - `urlOrPredicate` <[string]|[RegExp]|[Function]> Request URL string, regex or predicate receiving [Response] object.
|
1943 | - `options` <[Object]> Optional waiting parameters
|
1944 | - `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1945 | - returns: <[Promise]<[Response]>> Promise which resolves to the matched response.
|
1946 |
|
1947 | ```js
|
1948 | const firstResponse = await page.waitForResponse('https://example.com/resource');
|
1949 | const finalResponse = await page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);
|
1950 | return finalResponse.ok();
|
1951 | ```
|
1952 |
|
1953 | #### page.waitForSelector(selector[, options])
|
1954 | - `selector` <[string]> A selector of an element to wait for. See [working with selectors](#working-with-selectors) for more details.
|
1955 | - `options` <[Object]>
|
1956 | - `state` <"attached"|"detached"|"visible"|"hidden"> Defaults to `'visible'`. Can be either:
|
1957 | - `'attached'` - wait for element to be present in DOM.
|
1958 | - `'detached'` - wait for element to not be present in DOM.
|
1959 | - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element without any content or with `display:none` has an empty bounding box and is not considered visible.
|
1960 | - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or `visibility:hidden`. This is opposite to the `'visible'` option.
|
1961 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
1962 | - returns: <[Promise]<?[ElementHandle]>> Promise which resolves when element specified by selector satisfies `state` option. Resolves to `null` if waiting for `hidden` or `detached`.
|
1963 |
|
1964 | 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.
|
1965 |
|
1966 | This method works across navigations:
|
1967 | ```js
|
1968 | const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
|
1969 |
|
1970 | (async () => {
|
1971 | const browser = await chromium.launch();
|
1972 | const page = await browser.newPage();
|
1973 | let currentURL;
|
1974 | page
|
1975 | .waitForSelector('img')
|
1976 | .then(() => console.log('First URL with image: ' + currentURL));
|
1977 | for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
|
1978 | await page.goto(currentURL);
|
1979 | }
|
1980 | await browser.close();
|
1981 | })();
|
1982 | ```
|
1983 | Shortcut for [page.mainFrame().waitForSelector(selector[, options])](#framewaitforselectorselector-options).
|
1984 |
|
1985 | #### page.waitForTimeout(timeout)
|
1986 | - `timeout` <[number]> A timeout to wait for
|
1987 | - returns: <[Promise]>
|
1988 |
|
1989 | Returns a promise that resolves after the timeout.
|
1990 |
|
1991 | Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
|
1992 |
|
1993 | ```js
|
1994 | // wait for 1 second
|
1995 | await page.waitForTimeout(1000);
|
1996 | ```
|
1997 |
|
1998 | Shortcut for [page.mainFrame().waitForTimeout(timeout)](#pagewaitfortimeouttimeout).
|
1999 |
|
2000 | #### page.workers()
|
2001 | - returns: <[Array]<[Worker]>>
|
2002 | This method returns all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
|
2003 |
|
2004 | > **NOTE** This does not contain ServiceWorkers
|
2005 |
|
2006 | ### class: Frame
|
2007 |
|
2008 | At every point of time, page exposes its current frame tree via the [page.mainFrame()](#pagemainframe) and [frame.childFrames()](#framechildframes) methods.
|
2009 |
|
2010 | [Frame] object's lifecycle is controlled by three events, dispatched on the page object:
|
2011 | - ['frameattached'](#event-frameattached) - fired when the frame gets attached to the page. A Frame can be attached to the page only once.
|
2012 | - ['framenavigated'](#event-framenavigated) - fired when the frame commits navigation to a different URL.
|
2013 | - ['framedetached'](#event-framedetached) - fired when the frame gets detached from the page. A Frame can be detached from the page only once.
|
2014 |
|
2015 | An example of dumping frame tree:
|
2016 |
|
2017 | ```js
|
2018 | const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
|
2019 |
|
2020 | (async () => {
|
2021 | const browser = await firefox.launch();
|
2022 | const page = await browser.newPage();
|
2023 | await page.goto('https://www.google.com/chrome/browser/canary.html');
|
2024 | dumpFrameTree(page.mainFrame(), '');
|
2025 | await browser.close();
|
2026 |
|
2027 | function dumpFrameTree(frame, indent) {
|
2028 | console.log(indent + frame.url());
|
2029 | for (const child of frame.childFrames()) {
|
2030 | dumpFrameTree(child, indent + ' ');
|
2031 | }
|
2032 | }
|
2033 | })();
|
2034 | ```
|
2035 |
|
2036 | An example of getting text from an iframe element:
|
2037 |
|
2038 | ```js
|
2039 | const frame = page.frames().find(frame => frame.name() === 'myframe');
|
2040 | const text = await frame.$eval('.selector', element => element.textContent);
|
2041 | console.log(text);
|
2042 | ```
|
2043 |
|
2044 |
|
2045 | - [frame.$(selector)](#frameselector)
|
2046 | - [frame.$$(selector)](#frameselector-1)
|
2047 | - [frame.$eval(selector, pageFunction[, arg])](#frameevalselector-pagefunction-arg)
|
2048 | - [frame.$$eval(selector, pageFunction[, arg])](#frameevalselector-pagefunction-arg-1)
|
2049 | - [frame.addScriptTag(options)](#frameaddscripttagoptions)
|
2050 | - [frame.addStyleTag(options)](#frameaddstyletagoptions)
|
2051 | - [frame.check(selector, [options])](#framecheckselector-options)
|
2052 | - [frame.childFrames()](#framechildframes)
|
2053 | - [frame.click(selector[, options])](#frameclickselector-options)
|
2054 | - [frame.content()](#framecontent)
|
2055 | - [frame.dblclick(selector[, options])](#framedblclickselector-options)
|
2056 | - [frame.dispatchEvent(selector, type[, eventInit, options])](#framedispatcheventselector-type-eventinit-options)
|
2057 | - [frame.evaluate(pageFunction[, arg])](#frameevaluatepagefunction-arg)
|
2058 | - [frame.evaluateHandle(pageFunction[, arg])](#frameevaluatehandlepagefunction-arg)
|
2059 | - [frame.fill(selector, value[, options])](#framefillselector-value-options)
|
2060 | - [frame.focus(selector[, options])](#framefocusselector-options)
|
2061 | - [frame.frameElement()](#frameframeelement)
|
2062 | - [frame.getAttribute(selector, name[, options])](#framegetattributeselector-name-options)
|
2063 | - [frame.goto(url[, options])](#framegotourl-options)
|
2064 | - [frame.hover(selector[, options])](#framehoverselector-options)
|
2065 | - [frame.innerHTML(selector[, options])](#frameinnerhtmlselector-options)
|
2066 | - [frame.innerText(selector[, options])](#frameinnertextselector-options)
|
2067 | - [frame.isDetached()](#frameisdetached)
|
2068 | - [frame.name()](#framename)
|
2069 | - [frame.parentFrame()](#frameparentframe)
|
2070 | - [frame.press(selector, key[, options])](#framepressselector-key-options)
|
2071 | - [frame.selectOption(selector, values[, options])](#frameselectoptionselector-values-options)
|
2072 | - [frame.setContent(html[, options])](#framesetcontenthtml-options)
|
2073 | - [frame.setInputFiles(selector, files[, options])](#framesetinputfilesselector-files-options)
|
2074 | - [frame.textContent(selector[, options])](#frametextcontentselector-options)
|
2075 | - [frame.title()](#frametitle)
|
2076 | - [frame.type(selector, text[, options])](#frametypeselector-text-options)
|
2077 | - [frame.uncheck(selector, [options])](#frameuncheckselector-options)
|
2078 | - [frame.url()](#frameurl)
|
2079 | - [frame.waitForFunction(pageFunction[, arg, options])](#framewaitforfunctionpagefunction-arg-options)
|
2080 | - [frame.waitForLoadState([state[, options]])](#framewaitforloadstatestate-options)
|
2081 | - [frame.waitForNavigation([options])](#framewaitfornavigationoptions)
|
2082 | - [frame.waitForSelector(selector[, options])](#framewaitforselectorselector-options)
|
2083 | - [frame.waitForTimeout(timeout)](#framewaitfortimeouttimeout)
|
2084 |
|
2085 |
|
2086 | #### frame.$(selector)
|
2087 | - `selector` <[string]> A selector to query frame for. See [working with selectors](#working-with-selectors) for more details.
|
2088 | - returns: <[Promise]<?[ElementHandle]>> Promise which resolves to ElementHandle pointing to the frame element.
|
2089 |
|
2090 | The method finds an element matching the specified selector within the frame. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `null`.
|
2091 |
|
2092 | #### frame.$$(selector)
|
2093 | - `selector` <[string]> A selector to query frame for. See [working with selectors](#working-with-selectors) for more details.
|
2094 | - returns: <[Promise]<[Array]<[ElementHandle]>>> Promise which resolves to ElementHandles pointing to the frame elements.
|
2095 |
|
2096 | The method finds all elements matching the specified selector within the frame. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `[]`.
|
2097 |
|
2098 | #### frame.$eval(selector, pageFunction[, arg])
|
2099 | - `selector` <[string]> A selector to query frame for. See [working with selectors](#working-with-selectors) for more details.
|
2100 | - `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context
|
2101 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
2102 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
2103 |
|
2104 | The method finds an element matching the specified selector within the frame and passes it as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
|
2105 |
|
2106 | If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
|
2107 |
|
2108 | Examples:
|
2109 | ```js
|
2110 | const searchValue = await frame.$eval('#search', el => el.value);
|
2111 | const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
|
2112 | const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
|
2113 | ```
|
2114 |
|
2115 | #### frame.$$eval(selector, pageFunction[, arg])
|
2116 | - `selector` <[string]> A selector to query frame for. See [working with selectors](#working-with-selectors) for more details.
|
2117 | - `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context
|
2118 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
2119 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
2120 |
|
2121 | The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details.
|
2122 |
|
2123 | If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
|
2124 |
|
2125 | Examples:
|
2126 | ```js
|
2127 | const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
|
2128 | ```
|
2129 |
|
2130 | #### frame.addScriptTag(options)
|
2131 | - `options` <[Object]>
|
2132 | - `url` <[string]> URL of a script to be added.
|
2133 | - `path` <[string]> Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
2134 | - `content` <[string]> Raw JavaScript content to be injected into frame.
|
2135 | - `type` <[string]> Script type. Use 'module' in order to load a Javascript ES6 module. See [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.
|
2136 | - returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the script's onload fires or when the script content was injected into frame.
|
2137 |
|
2138 | Adds a `<script>` tag into the page with the desired url or content.
|
2139 |
|
2140 | #### frame.addStyleTag(options)
|
2141 | - `options` <[Object]>
|
2142 | - `url` <[string]> URL of the `<link>` tag.
|
2143 | - `path` <[string]> Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
2144 | - `content` <[string]> Raw CSS content to be injected into frame.
|
2145 | - returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
|
2146 |
|
2147 | Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
|
2148 |
|
2149 | #### frame.check(selector, [options])
|
2150 | - `selector` <[string]> A selector to search for checkbox to check. If there are multiple elements satisfying the selector, the first will be checked. See [working with selectors](#working-with-selectors) for more details.
|
2151 | - `options` <[Object]>
|
2152 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2153 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2154 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2155 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully checked. The Promise will be rejected if there is no element matching `selector`.
|
2156 |
|
2157 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks. Then, if the element is not already checked, this method scrolls the element into view and uses [elementHandle.click](#elementhandleclickoptions) to click in the center of the element.
|
2158 |
|
2159 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
2160 |
|
2161 | #### frame.childFrames()
|
2162 | - returns: <[Array]<[Frame]>>
|
2163 |
|
2164 | #### frame.click(selector[, options])
|
2165 | - `selector` <[string]> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked. See [working with selectors](#working-with-selectors) for more details.
|
2166 | - `options` <[Object]>
|
2167 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
2168 | - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
|
2169 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
2170 | - `position` <[Object]> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element.
|
2171 | - `x` <[number]>
|
2172 | - `y` <[number]>
|
2173 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
2174 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2175 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2176 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2177 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully clicked. The Promise will be rejected if there is no element matching `selector`.
|
2178 |
|
2179 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to click in the center of the element.
|
2180 |
|
2181 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
2182 |
|
2183 | #### frame.content()
|
2184 | - returns: <[Promise]<[string]>>
|
2185 |
|
2186 | Gets the full HTML contents of the frame, including the doctype.
|
2187 |
|
2188 | #### frame.dblclick(selector[, options])
|
2189 | - `selector` <[string]> A selector to search for element to double click. If there are multiple elements satisfying the selector, the first will be double clicked. See [working with selectors](#working-with-selectors) for more details.
|
2190 | - `options` <[Object]>
|
2191 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
2192 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
2193 | - `position` <[Object]> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element.
|
2194 | - `x` <[number]>
|
2195 | - `y` <[number]>
|
2196 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
2197 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2198 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2199 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2200 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully double clicked. The Promise will be rejected if there is no element matching `selector`.
|
2201 |
|
2202 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to double click in the center of the element.
|
2203 |
|
2204 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the actionability checks, the action is retried.
|
2205 |
|
2206 | Bear in mind that if the first click of the `dblclick()` triggers a navigation event, there will be an exception.
|
2207 |
|
2208 | > **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
|
2209 |
|
2210 | #### frame.dispatchEvent(selector, type[, eventInit, options])
|
2211 | - `selector` <[string]> A selector to search for element to use. If there are multiple elements satisfying the selector, the first will be double clicked. See [working with selectors](#working-with-selectors) for more details.
|
2212 | - `type` <[string]> DOM event type: `"click"`, `"dragstart"`, etc.
|
2213 | - `eventInit` <[Object]> event-specific initialization properties.
|
2214 | - `options` <[Object]>
|
2215 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2216 | - returns: <[Promise]>
|
2217 |
|
2218 | The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
|
2219 |
|
2220 | ```js
|
2221 | await frame.dispatchEvent('button#submit', 'click');
|
2222 | ```
|
2223 |
|
2224 | 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.
|
2225 |
|
2226 | Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
|
2227 | - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
|
2228 | - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
|
2229 | - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
|
2230 | - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
|
2231 | - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
|
2232 | - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
|
2233 | - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
|
2234 |
|
2235 | You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
|
2236 |
|
2237 | ```js
|
2238 | // Note you can only create DataTransfer in Chromium and Firefox
|
2239 | const dataTransfer = await frame.evaluateHandle(() => new DataTransfer());
|
2240 | await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });
|
2241 | ```
|
2242 |
|
2243 | #### frame.evaluate(pageFunction[, arg])
|
2244 | - `pageFunction` <[function]|[string]> Function to be evaluated in browser context
|
2245 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
2246 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
2247 |
|
2248 | If the function passed to the `frame.evaluate` returns a [Promise], then `frame.evaluate` would wait for the promise to resolve and return its value.
|
2249 |
|
2250 | If the function passed to the `frame.evaluate` returns a non-[Serializable] value, then `frame.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.
|
2251 |
|
2252 | ```js
|
2253 | const result = await frame.evaluate(([x, y]) => {
|
2254 | return Promise.resolve(x * y);
|
2255 | }, [7, 8]);
|
2256 | console.log(result); // prints "56"
|
2257 | ```
|
2258 |
|
2259 | A string can also be passed in instead of a function.
|
2260 |
|
2261 | ```js
|
2262 | console.log(await frame.evaluate('1 + 2')); // prints "3"
|
2263 | ```
|
2264 |
|
2265 | [ElementHandle] instances can be passed as an argument to the `frame.evaluate`:
|
2266 | ```js
|
2267 | const bodyHandle = await frame.$('body');
|
2268 | const html = await frame.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
|
2269 | await bodyHandle.dispose();
|
2270 | ```
|
2271 |
|
2272 | #### frame.evaluateHandle(pageFunction[, arg])
|
2273 | - `pageFunction` <[function]|[string]> Function to be evaluated in the page context
|
2274 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
2275 | - returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
|
2276 |
|
2277 | The only difference between `frame.evaluate` and `frame.evaluateHandle` is that `frame.evaluateHandle` returns in-page object (JSHandle).
|
2278 |
|
2279 | If the function, passed to the `frame.evaluateHandle`, returns a [Promise], then `frame.evaluateHandle` would wait for the promise to resolve and return its value.
|
2280 |
|
2281 | ```js
|
2282 | const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
|
2283 | aWindowHandle; // Handle for the window object.
|
2284 | ```
|
2285 |
|
2286 | A string can also be passed in instead of a function.
|
2287 |
|
2288 | ```js
|
2289 | const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.
|
2290 | ```
|
2291 |
|
2292 | [JSHandle] instances can be passed as an argument to the `frame.evaluateHandle`:
|
2293 | ```js
|
2294 | const aHandle = await frame.evaluateHandle(() => document.body);
|
2295 | const resultHandle = await frame.evaluateHandle(([body, suffix]) => body.innerHTML + suffix, [aHandle, 'hello']);
|
2296 | console.log(await resultHandle.jsonValue());
|
2297 | await resultHandle.dispose();
|
2298 | ```
|
2299 |
|
2300 | #### frame.fill(selector, value[, options])
|
2301 | - `selector` <[string]> A selector to query page for. See [working with selectors](#working-with-selectors) for more details.
|
2302 | - `value` <[string]> Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
|
2303 | - `options` <[Object]>
|
2304 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2305 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2306 | - returns: <[Promise]>
|
2307 |
|
2308 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
|
2309 | If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
|
2310 | Note that you can pass an empty string to clear the input field.
|
2311 |
|
2312 | To send fine-grained keyboard events, use [`frame.type`](#frametypeselector-text-options).
|
2313 |
|
2314 | #### frame.focus(selector[, options])
|
2315 | - `selector` <[string]> A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused. See [working with selectors](#working-with-selectors) for more details.
|
2316 | - `options` <[Object]>
|
2317 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2318 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.
|
2319 |
|
2320 | This method fetches an element with `selector` and focuses it.
|
2321 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
|
2322 |
|
2323 | #### frame.frameElement()
|
2324 | - returns: <[Promise]<[ElementHandle]>> Promise that resolves with a `frame` or `iframe` element handle which corresponds to this frame.
|
2325 |
|
2326 | This is an inverse of [elementHandle.contentFrame()](#elementhandlecontentframe). Note that returned handle actually belongs to the parent frame.
|
2327 |
|
2328 | This method throws an error if the frame has been detached before `frameElement()` returns.
|
2329 |
|
2330 | ```js
|
2331 | const frameElement = await frame.frameElement();
|
2332 | const contentFrame = await frameElement.contentFrame();
|
2333 | console.log(frame === contentFrame); // -> true
|
2334 | ```
|
2335 |
|
2336 | #### frame.getAttribute(selector, name[, options])
|
2337 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
2338 | - `name` <[string]> Attribute name to get the value for.
|
2339 | - `options` <[Object]>
|
2340 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2341 | - returns: <[Promise]<null|[string]>>
|
2342 |
|
2343 | Returns element attribute value.
|
2344 |
|
2345 | #### frame.goto(url[, options])
|
2346 | - `url` <[string]> URL to navigate frame to. The url should include scheme, e.g. `https://`.
|
2347 | - `options` <[Object]> Navigation parameters which might have the following properties:
|
2348 | - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2349 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
2350 | - `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
|
2351 | - `'load'` - consider navigation to be finished when the `load` event is fired.
|
2352 | - `'networkidle'` - consider navigation to be finished when there are no network connections for at least `500` ms.
|
2353 | - `referer` <[string]> Referer header value. If provided it will take preference over the referer header value set by [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders).
|
2354 | - returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
|
2355 |
|
2356 | `frame.goto` will throw an error if:
|
2357 | - there's an SSL error (e.g. in case of self-signed certificates).
|
2358 | - target URL is invalid.
|
2359 | - the `timeout` is exceeded during navigation.
|
2360 | - the remote server does not respond or is unreachable.
|
2361 | - the main resource failed to load.
|
2362 |
|
2363 | `frame.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).
|
2364 |
|
2365 | > **NOTE** `frame.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
|
2366 |
|
2367 | > **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
|
2368 |
|
2369 |
|
2370 | #### frame.hover(selector[, options])
|
2371 | - `selector` <[string]> A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered. See [working with selectors](#working-with-selectors) for more details.
|
2372 | - `options` <[Object]>
|
2373 | - `position` <[Object]> A point to hover relative to the top-left corner of element padding box. If not specified, hovers over some visible point of the element.
|
2374 | - `x` <[number]>
|
2375 | - `y` <[number]>
|
2376 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
2377 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2378 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2379 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully hovered. Promise gets rejected if there's no element matching `selector`.
|
2380 |
|
2381 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to hover over the center of the element.
|
2382 |
|
2383 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
2384 |
|
2385 | #### frame.innerHTML(selector[, options])
|
2386 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
2387 | - `options` <[Object]>
|
2388 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2389 | - returns: <[Promise]<[string]>>
|
2390 |
|
2391 | Resolves to the `element.innerHTML`.
|
2392 |
|
2393 | #### frame.innerText(selector[, options])
|
2394 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
2395 | - `options` <[Object]>
|
2396 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2397 | - returns: <[Promise]<[string]>>
|
2398 |
|
2399 | Resolves to the `element.innerText`.
|
2400 |
|
2401 | #### frame.isDetached()
|
2402 | - returns: <[boolean]>
|
2403 |
|
2404 | Returns `true` if the frame has been detached, or `false` otherwise.
|
2405 |
|
2406 | #### frame.name()
|
2407 | - returns: <[string]>
|
2408 |
|
2409 | Returns frame's name attribute as specified in the tag.
|
2410 |
|
2411 | If the name is empty, returns the id attribute instead.
|
2412 |
|
2413 | > **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed later.
|
2414 |
|
2415 | #### frame.parentFrame()
|
2416 | - returns: <?[Frame]> Parent frame, if any. Detached frames and main frames return `null`.
|
2417 |
|
2418 | #### frame.press(selector, key[, options])
|
2419 | - `selector` <[string]> A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
|
2420 | - `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
|
2421 | - `options` <[Object]>
|
2422 | - `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
|
2423 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2424 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2425 | - returns: <[Promise]>
|
2426 |
|
2427 | `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
|
2428 |
|
2429 | `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
|
2430 |
|
2431 | Following modification shortcuts are also suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
|
2432 |
|
2433 | Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
|
2434 |
|
2435 | If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
|
2436 |
|
2437 | Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
|
2438 |
|
2439 | #### frame.selectOption(selector, values[, options])
|
2440 | - `selector` <[string]> A selector to query frame for. See [working with selectors](#working-with-selectors) for more details.
|
2441 | - `values` <null|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.
|
2442 | - `value` <[string]> Matches by `option.value`.
|
2443 | - `label` <[string]> Matches by `option.label`.
|
2444 | - `index` <[number]> Matches by the index.
|
2445 | - `options` <[Object]>
|
2446 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2447 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2448 | - returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
|
2449 |
|
2450 | Triggers a `change` and `input` event once all the provided options have been selected.
|
2451 | If there's no `<select>` element matching `selector`, the method throws an error.
|
2452 |
|
2453 | ```js
|
2454 | // single selection matching the value
|
2455 | frame.selectOption('select#colors', 'blue');
|
2456 |
|
2457 | // single selection matching both the value and the label
|
2458 | frame.selectOption('select#colors', { label: 'Blue' });
|
2459 |
|
2460 | // multiple selection
|
2461 | frame.selectOption('select#colors', 'red', 'green', 'blue');
|
2462 | ```
|
2463 |
|
2464 | #### frame.setContent(html[, options])
|
2465 | - `html` <[string]> HTML markup to assign to the page.
|
2466 | - `options` <[Object]> Parameters which might have the following properties:
|
2467 | - `timeout` <[number]> Maximum time in milliseconds for resources to load, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2468 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
2469 | - `'domcontentloaded'` - consider setting content to be finished when the `DOMContentLoaded` event is fired.
|
2470 | - `'load'` - consider setting content to be finished when the `load` event is fired.
|
2471 | - `'networkidle'` - consider setting content to be finished when there are no network connections for at least `500` ms.
|
2472 | - returns: <[Promise]>
|
2473 |
|
2474 | #### frame.setInputFiles(selector, files[, options])
|
2475 | - `selector` <[string]> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked. See [working with selectors](#working-with-selectors) for more details.
|
2476 | - `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
|
2477 | - `name` <[string]> [File] name **required**
|
2478 | - `mimeType` <[string]> [File] type **required**
|
2479 | - `buffer` <[Buffer]> File content **required**
|
2480 | - `options` <[Object]>
|
2481 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2482 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2483 | - returns: <[Promise]>
|
2484 |
|
2485 | This method expects `selector` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
|
2486 |
|
2487 | Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
|
2488 |
|
2489 | #### frame.textContent(selector[, options])
|
2490 | - `selector` <[string]> A selector to search for an element. If there are multiple elements satisfying the selector, the first will be picked. See [working with selectors](#working-with-selectors) for more details.
|
2491 | - `options` <[Object]>
|
2492 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2493 | - returns: <[Promise]<null|[string]>>
|
2494 |
|
2495 | Resolves to the `element.textContent`.
|
2496 |
|
2497 |
|
2498 | #### frame.title()
|
2499 | - returns: <[Promise]<[string]>> The page's title.
|
2500 |
|
2501 | #### frame.type(selector, text[, options])
|
2502 | - `selector` <[string]> A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
|
2503 | - `text` <[string]> A text to type into a focused element.
|
2504 | - `options` <[Object]>
|
2505 | - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.
|
2506 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2507 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2508 | - returns: <[Promise]>
|
2509 |
|
2510 | Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [`frame.fill`](#framefillselector-value-options).
|
2511 |
|
2512 | To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).
|
2513 |
|
2514 | ```js
|
2515 | await frame.type('#mytextarea', 'Hello'); // Types instantly
|
2516 | await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
|
2517 | ```
|
2518 |
|
2519 | #### frame.uncheck(selector, [options])
|
2520 | - `selector` <[string]> A selector to search for uncheckbox to check. If there are multiple elements satisfying the selector, the first will be checked. See [working with selectors](#working-with-selectors) for more details.
|
2521 | - `options` <[Object]>
|
2522 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2523 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2524 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2525 | - returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully unchecked. The Promise will be rejected if there is no element matching `selector`.
|
2526 |
|
2527 | This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks. Then, if the element is not already unchecked, this method scrolls the element into view and uses [elementHandle.click](#elementhandleclickoptions) to click in the center of the element.
|
2528 |
|
2529 | If there's no element matching `selector`, the method waits until a matching element appears in the DOM. If the element is detached during the [actionability](./actionability.md) checks, the action is retried.
|
2530 |
|
2531 | #### frame.url()
|
2532 | - returns: <[string]>
|
2533 |
|
2534 | Returns frame's url.
|
2535 |
|
2536 | #### frame.waitForFunction(pageFunction[, arg, options])
|
2537 | - `pageFunction` <[function]|[string]> Function to be evaluated in browser context
|
2538 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
2539 | - `options` <[Object]> Optional waiting parameters
|
2540 | - `polling` <[number]|"raf"> If `polling` is `'raf'`, then `pageFunction` is constantly executed in `requestAnimationFrame` callback. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to `raf`.
|
2541 | - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2542 | - returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
|
2543 |
|
2544 | The `waitForFunction` can be used to observe viewport size change:
|
2545 | ```js
|
2546 | const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
|
2547 |
|
2548 | (async () => {
|
2549 | const browser = await firefox.launch();
|
2550 | const page = await browser.newPage();
|
2551 | const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
|
2552 | page.setViewportSize({width: 50, height: 50});
|
2553 | await watchDog;
|
2554 | await browser.close();
|
2555 | })();
|
2556 | ```
|
2557 |
|
2558 | To pass an argument from Node.js to the predicate of `frame.waitForFunction` function:
|
2559 |
|
2560 | ```js
|
2561 | const selector = '.foo';
|
2562 | await frame.waitForFunction(selector => !!document.querySelector(selector), selector);
|
2563 | ```
|
2564 |
|
2565 | #### frame.waitForLoadState([state[, options]])
|
2566 | - `state` <"load"|"domcontentloaded"|"networkidle"> Load state to wait for, defaults to `load`. If the state has been already reached while loading current document, the method resolves immediately.
|
2567 | - `'load'` - wait for the `load` event to be fired.
|
2568 | - `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
|
2569 | - `'networkidle'` - wait until there are no network connections for at least `500` ms.
|
2570 | - `options` <[Object]>
|
2571 | - `timeout` <[number]> Maximum waiting time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2572 | - returns: <[Promise]> Promise which resolves when the required load state has been reached.
|
2573 |
|
2574 | This resolves when the frame reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
|
2575 |
|
2576 | ```js
|
2577 | await frame.click('button'); // Click triggers navigation.
|
2578 | await frame.waitForLoadState(); // The promise resolves after 'load' event.
|
2579 | ```
|
2580 |
|
2581 | #### frame.waitForNavigation([options])
|
2582 | - `options` <[Object]> Navigation parameters which might have the following properties:
|
2583 | - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2584 | - `url` <[string]|[RegExp]|[Function]> URL string, URL regex pattern or predicate receiving [URL] to match while waiting for the navigation.
|
2585 | - `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider navigation succeeded, defaults to `load`. Events can be either:
|
2586 | - `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
|
2587 | - `'load'` - consider navigation to be finished when the `load` event is fired.
|
2588 | - `'networkidle'` - consider navigation to be finished when there are no network connections for at least `500` ms.
|
2589 | - returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
|
2590 |
|
2591 | This resolves when the frame navigates to a new URL. It is useful for when you run code
|
2592 | which will indirectly cause the frame to navigate. Consider this example:
|
2593 |
|
2594 | ```js
|
2595 | const [response] = await Promise.all([
|
2596 | frame.waitForNavigation(), // The navigation promise resolves after navigation has finished
|
2597 | frame.click('a.my-link'), // Clicking the link will indirectly cause a navigation
|
2598 | ]);
|
2599 | ```
|
2600 |
|
2601 | **NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
|
2602 |
|
2603 | #### frame.waitForSelector(selector[, options])
|
2604 | - `selector` <[string]> A selector of an element to wait for. See [working with selectors](#working-with-selectors) for more details.
|
2605 | - `options` <[Object]>
|
2606 | - `state` <"attached"|"detached"|"visible"|"hidden"> Defaults to `'visible'`. Can be either:
|
2607 | - `'attached'` - wait for element to be present in DOM.
|
2608 | - `'detached'` - wait for element to not be present in DOM.
|
2609 | - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element without any content or with `display:none` has an empty bounding box and is not considered visible.
|
2610 | - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or `visibility:hidden`. This is opposite to the `'visible'` option.
|
2611 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2612 | - returns: <[Promise]<?[ElementHandle]>> Promise which resolves when element specified by selector satisfies `state` option. Resolves to `null` if waiting for `hidden` or `detached`.
|
2613 |
|
2614 | 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.
|
2615 |
|
2616 | This method works across navigations:
|
2617 | ```js
|
2618 | const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
|
2619 |
|
2620 | (async () => {
|
2621 | const browser = await webkit.launch();
|
2622 | const page = await browser.newPage();
|
2623 | let currentURL;
|
2624 | page.mainFrame()
|
2625 | .waitForSelector('img')
|
2626 | .then(() => console.log('First URL with image: ' + currentURL));
|
2627 | for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
|
2628 | await page.goto(currentURL);
|
2629 | }
|
2630 | await browser.close();
|
2631 | })();
|
2632 | ```
|
2633 |
|
2634 | #### frame.waitForTimeout(timeout)
|
2635 | - `timeout` <[number]> A timeout to wait for
|
2636 | - returns: <[Promise]>
|
2637 |
|
2638 | Returns a promise that resolves after the timeout.
|
2639 |
|
2640 | Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
|
2641 |
|
2642 | ### class: ElementHandle
|
2643 | * extends: [JSHandle]
|
2644 |
|
2645 | ElementHandle represents an in-page DOM element. ElementHandles can be created with the [page.$](#pageselector) method.
|
2646 |
|
2647 | ```js
|
2648 | const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
|
2649 |
|
2650 | (async () => {
|
2651 | const browser = await chromium.launch();
|
2652 | const page = await browser.newPage();
|
2653 | await page.goto('https://example.com');
|
2654 | const hrefElement = await page.$('a');
|
2655 | await hrefElement.click();
|
2656 | // ...
|
2657 | })();
|
2658 | ```
|
2659 |
|
2660 | ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#jshandledispose). ElementHandles are auto-disposed when their origin frame gets navigated.
|
2661 |
|
2662 | ElementHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg) and [`page.evaluate()`](#pageevaluatepagefunction-arg) methods.
|
2663 |
|
2664 |
|
2665 | - [elementHandle.$(selector)](#elementhandleselector)
|
2666 | - [elementHandle.$$(selector)](#elementhandleselector-1)
|
2667 | - [elementHandle.$eval(selector, pageFunction[, arg])](#elementhandleevalselector-pagefunction-arg)
|
2668 | - [elementHandle.$$eval(selector, pageFunction[, arg])](#elementhandleevalselector-pagefunction-arg-1)
|
2669 | - [elementHandle.boundingBox()](#elementhandleboundingbox)
|
2670 | - [elementHandle.check([options])](#elementhandlecheckoptions)
|
2671 | - [elementHandle.click([options])](#elementhandleclickoptions)
|
2672 | - [elementHandle.contentFrame()](#elementhandlecontentframe)
|
2673 | - [elementHandle.dblclick([options])](#elementhandledblclickoptions)
|
2674 | - [elementHandle.dispatchEvent(type[, eventInit])](#elementhandledispatcheventtype-eventinit)
|
2675 | - [elementHandle.fill(value[, options])](#elementhandlefillvalue-options)
|
2676 | - [elementHandle.focus()](#elementhandlefocus)
|
2677 | - [elementHandle.getAttribute(name)](#elementhandlegetattributename)
|
2678 | - [elementHandle.hover([options])](#elementhandlehoveroptions)
|
2679 | - [elementHandle.innerHTML()](#elementhandleinnerhtml)
|
2680 | - [elementHandle.innerText()](#elementhandleinnertext)
|
2681 | - [elementHandle.ownerFrame()](#elementhandleownerframe)
|
2682 | - [elementHandle.press(key[, options])](#elementhandlepresskey-options)
|
2683 | - [elementHandle.screenshot([options])](#elementhandlescreenshotoptions)
|
2684 | - [elementHandle.scrollIntoViewIfNeeded([options])](#elementhandlescrollintoviewifneededoptions)
|
2685 | - [elementHandle.selectOption(values[, options])](#elementhandleselectoptionvalues-options)
|
2686 | - [elementHandle.selectText([options])](#elementhandleselecttextoptions)
|
2687 | - [elementHandle.setInputFiles(files[, options])](#elementhandlesetinputfilesfiles-options)
|
2688 | - [elementHandle.textContent()](#elementhandletextcontent)
|
2689 | - [elementHandle.toString()](#elementhandletostring)
|
2690 | - [elementHandle.type(text[, options])](#elementhandletypetext-options)
|
2691 | - [elementHandle.uncheck([options])](#elementhandleuncheckoptions)
|
2692 |
|
2693 |
|
2694 | - [jsHandle.asElement()](#jshandleaselement)
|
2695 | - [jsHandle.dispose()](#jshandledispose)
|
2696 | - [jsHandle.evaluate(pageFunction[, arg])](#jshandleevaluatepagefunction-arg)
|
2697 | - [jsHandle.evaluateHandle(pageFunction[, arg])](#jshandleevaluatehandlepagefunction-arg)
|
2698 | - [jsHandle.getProperties()](#jshandlegetproperties)
|
2699 | - [jsHandle.getProperty(propertyName)](#jshandlegetpropertypropertyname)
|
2700 | - [jsHandle.jsonValue()](#jshandlejsonvalue)
|
2701 |
|
2702 |
|
2703 | #### elementHandle.$(selector)
|
2704 | - `selector` <[string]> A selector to query element for. See [working with selectors](#working-with-selectors) for more details.
|
2705 | - returns: <[Promise]<?[ElementHandle]>>
|
2706 |
|
2707 | The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `null`.
|
2708 |
|
2709 | #### elementHandle.$$(selector)
|
2710 | - `selector` <[string]> A selector to query element for. See [working with selectors](#working-with-selectors) for more details.
|
2711 | - returns: <[Promise]<[Array]<[ElementHandle]>>>
|
2712 |
|
2713 | The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `[]`.
|
2714 |
|
2715 | #### elementHandle.$eval(selector, pageFunction[, arg])
|
2716 | - `selector` <[string]> A selector to query element for. See [working with selectors](#working-with-selectors) for more details.
|
2717 | - `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context
|
2718 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
2719 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
2720 |
|
2721 | The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
|
2722 |
|
2723 | If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
|
2724 |
|
2725 | Examples:
|
2726 | ```js
|
2727 | const tweetHandle = await page.$('.tweet');
|
2728 | expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
|
2729 | expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
|
2730 | ```
|
2731 |
|
2732 | #### elementHandle.$$eval(selector, pageFunction[, arg])
|
2733 | - `selector` <[string]> A selector to query element for. See [working with selectors](#working-with-selectors) for more details.
|
2734 | - `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context
|
2735 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
2736 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
2737 |
|
2738 | 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 `pageFunction`. See [Working with selectors](#working-with-selectors) for more details.
|
2739 |
|
2740 | If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
|
2741 |
|
2742 | Examples:
|
2743 | ```html
|
2744 | <div class="feed">
|
2745 | <div class="tweet">Hello!</div>
|
2746 | <div class="tweet">Hi!</div>
|
2747 | </div>
|
2748 | ```
|
2749 | ```js
|
2750 | const feedHandle = await page.$('.feed');
|
2751 | expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!']);
|
2752 | ```
|
2753 |
|
2754 | #### elementHandle.boundingBox()
|
2755 | - returns: <[Promise]<?[Object]>>
|
2756 | - `x` <[number]> the x coordinate of the element in pixels.
|
2757 | - `y` <[number]> the y coordinate of the element in pixels.
|
2758 | - width <[number]> the width of the element in pixels.
|
2759 | - height <[number]> the height of the element in pixels.
|
2760 |
|
2761 | This method returns the bounding box of the element (relative to the main frame), or `null` if the element is not visible.
|
2762 |
|
2763 | #### elementHandle.check([options])
|
2764 | - `options` <[Object]>
|
2765 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2766 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2767 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2768 | - returns: <[Promise]> Promise which resolves when the element is successfully checked. Promise gets rejected if the operation fails.
|
2769 |
|
2770 | This method waits for [actionability](./actionability.md) checks. Then, if the element is not already checked, this method scrolls the element into view and uses [elementHandle.click](#elementhandleclickoptions) to click in the center of the element.
|
2771 |
|
2772 | #### elementHandle.click([options])
|
2773 | - `options` <[Object]>
|
2774 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
2775 | - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
|
2776 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
2777 | - `position` <[Object]> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element.
|
2778 | - `x` <[number]>
|
2779 | - `y` <[number]>
|
2780 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
2781 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2782 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2783 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2784 | - returns: <[Promise]> Promise which resolves when the element is successfully clicked. Promise gets rejected if the element is detached from DOM.
|
2785 |
|
2786 | This method waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to click in the center of the element.
|
2787 |
|
2788 | If the element is detached from DOM, the method throws an error.
|
2789 |
|
2790 | #### elementHandle.contentFrame()
|
2791 | - returns: <[Promise]<?[Frame]>> Resolves to the content frame for element handles referencing iframe nodes, or `null` otherwise
|
2792 |
|
2793 | #### elementHandle.dblclick([options])
|
2794 | - `options` <[Object]>
|
2795 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
2796 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
2797 | - `position` <[Object]> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element.
|
2798 | - `x` <[number]>
|
2799 | - `y` <[number]>
|
2800 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
2801 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2802 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2803 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2804 | - returns: <[Promise]> Promise which resolves when the element is successfully double clicked. Promise gets rejected if the element is detached from DOM.
|
2805 |
|
2806 | This method waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to double click in the center of the element.
|
2807 |
|
2808 | If the element is detached from DOM, the method throws an error.
|
2809 |
|
2810 | Bear in mind that if the first click of the `dblclick()` triggers a navigation event, there will be an exception.
|
2811 |
|
2812 | > **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
|
2813 |
|
2814 | #### elementHandle.dispatchEvent(type[, eventInit])
|
2815 | - `type` <[string]> DOM event type: `"click"`, `"dragstart"`, etc.
|
2816 | - `eventInit` <[Object]> event-specific initialization properties.
|
2817 | - returns: <[Promise]>
|
2818 |
|
2819 | The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
|
2820 |
|
2821 | ```js
|
2822 | await elementHandle.dispatchEvent('click');
|
2823 | ```
|
2824 |
|
2825 | 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.
|
2826 |
|
2827 | Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
|
2828 | - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
|
2829 | - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
|
2830 | - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
|
2831 | - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
|
2832 | - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
|
2833 | - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
|
2834 | - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
|
2835 |
|
2836 | You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
|
2837 |
|
2838 | ```js
|
2839 | // Note you can only create DataTransfer in Chromium and Firefox
|
2840 | const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
|
2841 | await elementHandle.dispatchEvent('dragstart', { dataTransfer });
|
2842 | ```
|
2843 |
|
2844 | #### elementHandle.fill(value[, options])
|
2845 | - `value` <[string]> Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
|
2846 | - `options` <[Object]>
|
2847 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2848 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2849 | - returns: <[Promise]>
|
2850 |
|
2851 | This method waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
|
2852 | If the element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
|
2853 | Note that you can pass an empty string to clear the input field.
|
2854 |
|
2855 | #### elementHandle.focus()
|
2856 | - returns: <[Promise]>
|
2857 |
|
2858 | Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
|
2859 |
|
2860 | #### elementHandle.getAttribute(name)
|
2861 | - `name` <[string]> Attribute name to get the value for.
|
2862 | - returns: <[Promise]<null|[string]>>
|
2863 |
|
2864 | Returns element attribute value.
|
2865 |
|
2866 | #### elementHandle.hover([options])
|
2867 | - `options` <[Object]>
|
2868 | - `position` <[Object]> A point to hover relative to the top-left corner of element padding box. If not specified, hovers over some visible point of the element.
|
2869 | - `x` <[number]>
|
2870 | - `y` <[number]>
|
2871 | - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
|
2872 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
2873 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2874 | - returns: <[Promise]> Promise which resolves when the element is successfully hovered.
|
2875 |
|
2876 | This method waits for [actionability](./actionability.md) checks, then scrolls the element into view if needed and uses [page.mouse](#pagemouse) to hover over the center of the element.
|
2877 |
|
2878 | If the element is detached from DOM, the method throws an error.
|
2879 |
|
2880 | #### elementHandle.innerHTML()
|
2881 | - returns: <[Promise]<[string]>> Resolves to the `element.innerHTML`.
|
2882 |
|
2883 | #### elementHandle.innerText()
|
2884 | - returns: <[Promise]<[string]>> Resolves to the `element.innerText`.
|
2885 |
|
2886 | #### elementHandle.ownerFrame()
|
2887 | - returns: <[Promise]<?[Frame]>> Returns the frame containing the given element.
|
2888 |
|
2889 | #### elementHandle.press(key[, options])
|
2890 | - `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
|
2891 | - `options` <[Object]>
|
2892 | - `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
|
2893 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2894 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2895 | - returns: <[Promise]>
|
2896 |
|
2897 | Focuses the element, and then uses [`keyboard.down`](#keyboarddownkey) and [`keyboard.up`](#keyboardupkey).
|
2898 |
|
2899 | `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
|
2900 |
|
2901 | `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
|
2902 |
|
2903 | Following modification shortcuts are also suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
|
2904 |
|
2905 | Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
|
2906 |
|
2907 | If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
|
2908 |
|
2909 | Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
|
2910 |
|
2911 | #### elementHandle.screenshot([options])
|
2912 | - `options` <[Object]> Screenshot options.
|
2913 | - `path` <[string]> The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.
|
2914 | - `type` <"png"|"jpeg"> Specify screenshot type, defaults to `png`.
|
2915 | - `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.
|
2916 | - `omitBackground` <[boolean]> Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images. Defaults to `false`.
|
2917 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2918 | - returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with the captured screenshot.
|
2919 |
|
2920 | This method waits for the [actionability](./actionability.md) checks, then scrolls element into view before taking a screenshot. If the element is detached from DOM, the method throws an error.
|
2921 |
|
2922 | #### elementHandle.scrollIntoViewIfNeeded([options])
|
2923 | - `options` <[Object]>
|
2924 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2925 | - returns: <[Promise]>
|
2926 |
|
2927 | This method waits for [actionability](./actionability.md) checks, then tries to scroll element into view, unless it is completely visible as defined by [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s ```ratio```.
|
2928 |
|
2929 | Throws when ```elementHandle``` does not point to an element [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
|
2930 |
|
2931 | #### elementHandle.selectOption(values[, options])
|
2932 | - `values` <null|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.
|
2933 | - `value` <[string]> Matches by `option.value`.
|
2934 | - `label` <[string]> Matches by `option.label`.
|
2935 | - `index` <[number]> Matches by the index.
|
2936 | - `options` <[Object]>
|
2937 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2938 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2939 | - returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
|
2940 |
|
2941 | Triggers a `change` and `input` event once all the provided options have been selected.
|
2942 | If element is not a `<select>` element, the method throws an error.
|
2943 |
|
2944 | ```js
|
2945 | // single selection matching the value
|
2946 | handle.selectOption('blue');
|
2947 |
|
2948 | // single selection matching both the value and the label
|
2949 | handle.selectOption({ label: 'Blue' });
|
2950 |
|
2951 | // multiple selection
|
2952 | handle.selectOption('red', 'green', 'blue');
|
2953 |
|
2954 | // multiple selection for blue, red and second option
|
2955 | handle.selectOption({ value: 'blue' }, { index: 2 }, 'red');
|
2956 | ```
|
2957 |
|
2958 | #### elementHandle.selectText([options])
|
2959 | - `options` <[Object]>
|
2960 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2961 | - returns: <[Promise]>
|
2962 |
|
2963 | This method waits for [actionability](./actionability.md) checks, then focuses the element and selects all its text content.
|
2964 |
|
2965 | #### elementHandle.setInputFiles(files[, options])
|
2966 | - `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
|
2967 | - `name` <[string]> [File] name **required**
|
2968 | - `mimeType` <[string]> [File] type **required**
|
2969 | - `buffer` <[Buffer]> File content **required**
|
2970 | - `options` <[Object]>
|
2971 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2972 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2973 | - returns: <[Promise]>
|
2974 |
|
2975 | This method expects `elementHandle` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
|
2976 |
|
2977 | Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
|
2978 |
|
2979 | #### elementHandle.textContent()
|
2980 | - returns: <[Promise]<null|[string]>> Resolves to the `node.textContent`.
|
2981 |
|
2982 | #### elementHandle.toString()
|
2983 | - returns: <[string]>
|
2984 |
|
2985 | #### elementHandle.type(text[, options])
|
2986 | - `text` <[string]> A text to type into a focused element.
|
2987 | - `options` <[Object]>
|
2988 | - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.
|
2989 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
2990 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
2991 | - returns: <[Promise]>
|
2992 |
|
2993 | Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
|
2994 |
|
2995 | To press a special key, like `Control` or `ArrowDown`, use [`elementHandle.press`](#elementhandlepresskey-options).
|
2996 |
|
2997 | ```js
|
2998 | await elementHandle.type('Hello'); // Types instantly
|
2999 | await elementHandle.type('World', {delay: 100}); // Types slower, like a user
|
3000 | ```
|
3001 |
|
3002 | An example of typing into a text field and then submitting the form:
|
3003 | ```js
|
3004 | const elementHandle = await page.$('input');
|
3005 | await elementHandle.type('some text');
|
3006 | await elementHandle.press('Enter');
|
3007 | ```
|
3008 |
|
3009 | #### elementHandle.uncheck([options])
|
3010 | - `options` <[Object]>
|
3011 | - `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
|
3012 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
3013 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
3014 | - returns: <[Promise]> Promise which resolves when the element is successfully unchecked. Promise gets rejected if the operation fails.
|
3015 |
|
3016 | This method waits for [actionability](./actionability.md) checks. Then, if the element is not already unchecked, this method scrolls the element into view and uses [elementHandle.click](#elementhandleclickoptions) to click in the center of the element.
|
3017 |
|
3018 | ### class: JSHandle
|
3019 |
|
3020 | JSHandle represents an in-page JavaScript object. JSHandles can be created with the [page.evaluateHandle](#pageevaluatehandlepagefunction-arg) method.
|
3021 |
|
3022 | ```js
|
3023 | const windowHandle = await page.evaluateHandle(() => window);
|
3024 | // ...
|
3025 | ```
|
3026 |
|
3027 | JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is [disposed](#jshandledispose). JSHandles are auto-disposed when their origin frame gets navigated or the parent context gets destroyed.
|
3028 |
|
3029 | JSHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg), [`page.evaluate()`](#pageevaluatepagefunction-arg) and [`page.evaluateHandle()`](#pageevaluatehandlepagefunction-arg) methods.
|
3030 |
|
3031 |
|
3032 | - [jsHandle.asElement()](#jshandleaselement)
|
3033 | - [jsHandle.dispose()](#jshandledispose)
|
3034 | - [jsHandle.evaluate(pageFunction[, arg])](#jshandleevaluatepagefunction-arg)
|
3035 | - [jsHandle.evaluateHandle(pageFunction[, arg])](#jshandleevaluatehandlepagefunction-arg)
|
3036 | - [jsHandle.getProperties()](#jshandlegetproperties)
|
3037 | - [jsHandle.getProperty(propertyName)](#jshandlegetpropertypropertyname)
|
3038 | - [jsHandle.jsonValue()](#jshandlejsonvalue)
|
3039 |
|
3040 |
|
3041 | #### jsHandle.asElement()
|
3042 | - returns: <?[ElementHandle]>
|
3043 |
|
3044 | Returns either `null` or the object handle itself, if the object handle is an instance of [ElementHandle].
|
3045 |
|
3046 | #### jsHandle.dispose()
|
3047 | - returns: <[Promise]> Promise which resolves when the object handle is successfully disposed.
|
3048 |
|
3049 | The `jsHandle.dispose` method stops referencing the element handle.
|
3050 |
|
3051 | #### jsHandle.evaluate(pageFunction[, arg])
|
3052 | - `pageFunction` <[function]\([Object]\)> Function to be evaluated in browser context
|
3053 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
3054 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
3055 |
|
3056 | This method passes this handle as the first argument to `pageFunction`.
|
3057 |
|
3058 | If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its value.
|
3059 |
|
3060 | Examples:
|
3061 | ```js
|
3062 | const tweetHandle = await page.$('.tweet .retweets');
|
3063 | expect(await tweetHandle.evaluate((node, suffix) => node.innerText, ' retweets')).toBe('10 retweets');
|
3064 | ```
|
3065 |
|
3066 | #### jsHandle.evaluateHandle(pageFunction[, arg])
|
3067 | - `pageFunction` <[function]|[string]> Function to be evaluated
|
3068 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
3069 | - returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
|
3070 |
|
3071 | This method passes this handle as the first argument to `pageFunction`.
|
3072 |
|
3073 | The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle` returns in-page object (JSHandle).
|
3074 |
|
3075 | If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would wait for the promise to resolve and return its value.
|
3076 |
|
3077 | See [page.evaluateHandle()](#pageevaluatehandlepagefunction-arg) for more details.
|
3078 |
|
3079 | #### jsHandle.getProperties()
|
3080 | - returns: <[Promise]<[Map]<[string], [JSHandle]>>>
|
3081 |
|
3082 | The method returns a map with **own property names** as keys and JSHandle instances for the property values.
|
3083 |
|
3084 | ```js
|
3085 | const handle = await page.evaluateHandle(() => ({window, document}));
|
3086 | const properties = await handle.getProperties();
|
3087 | const windowHandle = properties.get('window');
|
3088 | const documentHandle = properties.get('document');
|
3089 | await handle.dispose();
|
3090 | ```
|
3091 |
|
3092 | #### jsHandle.getProperty(propertyName)
|
3093 | - `propertyName` <[string]> property to get
|
3094 | - returns: <[Promise]<[JSHandle]>>
|
3095 |
|
3096 | Fetches a single property from the referenced object.
|
3097 |
|
3098 | #### jsHandle.jsonValue()
|
3099 | - returns: <[Promise]<[Object]>>
|
3100 |
|
3101 | Returns a JSON representation of the object. If the object has a
|
3102 | [`toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior)
|
3103 | function, it **will not be called**.
|
3104 |
|
3105 | > **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw an error if the object has circular references.
|
3106 |
|
3107 | ### class: ConsoleMessage
|
3108 |
|
3109 | [ConsoleMessage] objects are dispatched by page via the ['console'](#event-console) event.
|
3110 |
|
3111 |
|
3112 | - [consoleMessage.args()](#consolemessageargs)
|
3113 | - [consoleMessage.location()](#consolemessagelocation)
|
3114 | - [consoleMessage.text()](#consolemessagetext)
|
3115 | - [consoleMessage.type()](#consolemessagetype)
|
3116 |
|
3117 |
|
3118 | #### consoleMessage.args()
|
3119 | - returns: <[Array]<[JSHandle]>>
|
3120 |
|
3121 | #### consoleMessage.location()
|
3122 | - returns: <[Object]>
|
3123 | - `url` <[string]> Optional URL of the resource if available.
|
3124 | - `lineNumber` <[number]> Optional 0-based line number in the resource if available.
|
3125 | - `columnNumber` <[number]> Optional 0-based column number in the resource if available.
|
3126 |
|
3127 | #### consoleMessage.text()
|
3128 | - returns: <[string]>
|
3129 |
|
3130 | #### consoleMessage.type()
|
3131 | - returns: <[string]>
|
3132 |
|
3133 | One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`, `'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`, `'count'`, `'timeEnd'`.
|
3134 |
|
3135 | ### class: Dialog
|
3136 |
|
3137 | [Dialog] objects are dispatched by page via the ['dialog'](#event-dialog) event.
|
3138 |
|
3139 | An example of using `Dialog` class:
|
3140 | ```js
|
3141 | const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
|
3142 |
|
3143 | (async () => {
|
3144 | const browser = await chromium.launch();
|
3145 | const page = await browser.newPage();
|
3146 | page.on('dialog', async dialog => {
|
3147 | console.log(dialog.message());
|
3148 | await dialog.dismiss();
|
3149 | await browser.close();
|
3150 | });
|
3151 | page.evaluate(() => alert('1'));
|
3152 | })();
|
3153 | ```
|
3154 |
|
3155 |
|
3156 | - [dialog.accept([promptText])](#dialogacceptprompttext)
|
3157 | - [dialog.defaultValue()](#dialogdefaultvalue)
|
3158 | - [dialog.dismiss()](#dialogdismiss)
|
3159 | - [dialog.message()](#dialogmessage)
|
3160 | - [dialog.type()](#dialogtype)
|
3161 |
|
3162 |
|
3163 | #### dialog.accept([promptText])
|
3164 | - `promptText` <[string]> A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt.
|
3165 | - returns: <[Promise]> Promise which resolves when the dialog has been accepted.
|
3166 |
|
3167 | #### dialog.defaultValue()
|
3168 | - returns: <[string]> If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
|
3169 |
|
3170 | #### dialog.dismiss()
|
3171 | - returns: <[Promise]> Promise which resolves when the dialog has been dismissed.
|
3172 |
|
3173 | #### dialog.message()
|
3174 | - returns: <[string]> A message displayed in the dialog.
|
3175 |
|
3176 | #### dialog.type()
|
3177 | - returns: <[string]> Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
|
3178 |
|
3179 |
|
3180 | ### class: Download
|
3181 |
|
3182 | [Download] objects are dispatched by page via the ['download'](#event-download) event.
|
3183 |
|
3184 | All the downloaded files belonging to the browser context are deleted when the browser context is closed. All downloaded files are deleted when the browser closes.
|
3185 |
|
3186 | Download event is emitted once the download starts. Download path becomes available
|
3187 | once download completes:
|
3188 |
|
3189 | ```js
|
3190 | const [ download ] = await Promise.all([
|
3191 | page.waitForEvent('download'), // wait for download to start
|
3192 | page.click('a')
|
3193 | ]);
|
3194 | // wait for download to complete
|
3195 | const path = await download.path();
|
3196 | ...
|
3197 | ```
|
3198 |
|
3199 | > **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.
|
3200 |
|
3201 |
|
3202 | - [download.createReadStream()](#downloadcreatereadstream)
|
3203 | - [download.delete()](#downloaddelete)
|
3204 | - [download.failure()](#downloadfailure)
|
3205 | - [download.path()](#downloadpath)
|
3206 | - [download.saveAs(path)](#downloadsaveaspath)
|
3207 | - [download.suggestedFilename()](#downloadsuggestedfilename)
|
3208 | - [download.url()](#downloadurl)
|
3209 |
|
3210 |
|
3211 | #### download.createReadStream()
|
3212 | - returns: <[Promise]<null|[Readable]>>
|
3213 |
|
3214 | Returns readable stream for current download or `null` if download failed.
|
3215 |
|
3216 | #### download.delete()
|
3217 | - returns: <[Promise]>
|
3218 |
|
3219 | Deletes the downloaded file.
|
3220 |
|
3221 | #### download.failure()
|
3222 | - returns: <[Promise]<null|[string]>>
|
3223 |
|
3224 | Returns download error if any.
|
3225 |
|
3226 | #### download.path()
|
3227 | - returns: <[Promise]<null|[string]>>
|
3228 |
|
3229 | Returns path to the downloaded file in case of successful download.
|
3230 |
|
3231 | #### download.saveAs(path)
|
3232 | - `path` <[string]> Path where the download should be saved.
|
3233 | - returns: <[Promise]>
|
3234 |
|
3235 | Saves the download to a user-specified path.
|
3236 |
|
3237 | #### download.suggestedFilename()
|
3238 | - returns: <[string]>
|
3239 |
|
3240 | 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.
|
3241 |
|
3242 | #### download.url()
|
3243 | - returns: <[string]>
|
3244 |
|
3245 | Returns downloaded url.
|
3246 |
|
3247 |
|
3248 | ### class: FileChooser
|
3249 |
|
3250 | [FileChooser] objects are dispatched by the page in the ['filechooser'](#event-filechooser) event.
|
3251 |
|
3252 | ```js
|
3253 | page.on('filechooser', async (fileChooser) => {
|
3254 | await fileChooser.setFiles('/tmp/myfile.pdf');
|
3255 | });
|
3256 | ```
|
3257 |
|
3258 |
|
3259 | - [fileChooser.element()](#filechooserelement)
|
3260 | - [fileChooser.isMultiple()](#filechooserismultiple)
|
3261 | - [fileChooser.page()](#filechooserpage)
|
3262 | - [fileChooser.setFiles(files[, options])](#filechoosersetfilesfiles-options)
|
3263 |
|
3264 |
|
3265 | #### fileChooser.element()
|
3266 | - returns: <[ElementHandle]>
|
3267 |
|
3268 | Returns input element associated with this file chooser.
|
3269 |
|
3270 | #### fileChooser.isMultiple()
|
3271 | - returns: <[boolean]>
|
3272 |
|
3273 | Returns whether this file chooser accepts multiple files.
|
3274 |
|
3275 | #### fileChooser.page()
|
3276 | - returns: <[Page]>
|
3277 |
|
3278 | Returns page this file chooser belongs to.
|
3279 |
|
3280 | #### fileChooser.setFiles(files[, options])
|
3281 | - `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
|
3282 | - `name` <[string]> [File] name **required**
|
3283 | - `mimeType` <[string]> [File] type **required**
|
3284 | - `buffer` <[Buffer]> File content **required**
|
3285 | - `options` <[Object]>
|
3286 | - `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
|
3287 | - `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
|
3288 | - returns: <[Promise]>
|
3289 |
|
3290 | Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
|
3291 |
|
3292 | ### class: Keyboard
|
3293 |
|
3294 | Keyboard provides an api for managing a virtual keyboard. The high level api is [`keyboard.type`](#keyboardtypetext-options), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.
|
3295 |
|
3296 | For finer control, you can use [`keyboard.down`](#keyboarddownkey), [`keyboard.up`](#keyboardupkey), and [`keyboard.insertText`](#keyboardinserttexttext) to manually fire events as if they were generated from a real keyboard.
|
3297 |
|
3298 | An example of holding down `Shift` in order to select and delete some text:
|
3299 | ```js
|
3300 | await page.keyboard.type('Hello World!');
|
3301 | await page.keyboard.press('ArrowLeft');
|
3302 |
|
3303 | await page.keyboard.down('Shift');
|
3304 | for (let i = 0; i < ' World'.length; i++)
|
3305 | await page.keyboard.press('ArrowLeft');
|
3306 | await page.keyboard.up('Shift');
|
3307 |
|
3308 | await page.keyboard.press('Backspace');
|
3309 | // Result text will end up saying 'Hello!'
|
3310 | ```
|
3311 |
|
3312 | An example of pressing `A`
|
3313 | ```js
|
3314 | await page.keyboard.press('Shift+KeyA');
|
3315 | // or
|
3316 | await page.keyboard.press('Shift+A');
|
3317 | ```
|
3318 |
|
3319 | > **NOTE** On MacOS, keyboard shortcuts like `⌘ A` -> Select All do not work. See [#1313](https://github.com/GoogleChrome/puppeteer/issues/1313)
|
3320 |
|
3321 |
|
3322 | - [keyboard.down(key)](#keyboarddownkey)
|
3323 | - [keyboard.insertText(text)](#keyboardinserttexttext)
|
3324 | - [keyboard.press(key[, options])](#keyboardpresskey-options)
|
3325 | - [keyboard.type(text[, options])](#keyboardtypetext-options)
|
3326 | - [keyboard.up(key)](#keyboardupkey)
|
3327 |
|
3328 |
|
3329 | #### keyboard.down(key)
|
3330 | - `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
|
3331 | - returns: <[Promise]>
|
3332 |
|
3333 | Dispatches a `keydown` event.
|
3334 |
|
3335 | `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
|
3336 |
|
3337 | `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
|
3338 |
|
3339 | Following modification shortcuts are also suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
|
3340 |
|
3341 | Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
|
3342 |
|
3343 | If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
|
3344 |
|
3345 | If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier key, use [`keyboard.up`](#keyboardupkey).
|
3346 |
|
3347 | After the key is pressed once, subsequent calls to [`keyboard.down`](#keyboarddownkey) will have [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key, use [`keyboard.up`](#keyboardupkey).
|
3348 |
|
3349 | > **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
|
3350 |
|
3351 | #### keyboard.insertText(text)
|
3352 | - `text` <[string]> Sets input to the specified text value.
|
3353 | - returns: <[Promise]>
|
3354 |
|
3355 | Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.
|
3356 |
|
3357 | ```js
|
3358 | page.keyboard.insertText('嗨');
|
3359 | ```
|
3360 |
|
3361 | > **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper case.
|
3362 |
|
3363 | #### keyboard.press(key[, options])
|
3364 | - `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
|
3365 | - `options` <[Object]>
|
3366 | - `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
|
3367 | - returns: <[Promise]>
|
3368 |
|
3369 | `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
|
3370 |
|
3371 | `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
|
3372 |
|
3373 | Following modification shortcuts are also suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
|
3374 |
|
3375 | Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
|
3376 |
|
3377 | If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
|
3378 |
|
3379 | Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
|
3380 |
|
3381 | ```js
|
3382 | const page = await browser.newPage();
|
3383 | await page.goto('https://keycode.info');
|
3384 | await page.keyboard.press('A');
|
3385 | await page.screenshot({ path: 'A.png' });
|
3386 | await page.keyboard.press('ArrowLeft');
|
3387 | await page.screenshot({ path: 'ArrowLeft.png' });
|
3388 | await page.keyboard.press('Shift+O');
|
3389 | await page.screenshot({ path: 'O.png' });
|
3390 | await browser.close();
|
3391 | ```
|
3392 |
|
3393 | Shortcut for [`keyboard.down`](#keyboarddownkey) and [`keyboard.up`](#keyboardupkey).
|
3394 |
|
3395 | #### keyboard.type(text[, options])
|
3396 | - `text` <[string]> A text to type into a focused element.
|
3397 | - `options` <[Object]>
|
3398 | - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.
|
3399 | - returns: <[Promise]>
|
3400 |
|
3401 | Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
|
3402 |
|
3403 | To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).
|
3404 |
|
3405 | ```js
|
3406 | await page.keyboard.type('Hello'); // Types instantly
|
3407 | await page.keyboard.type('World', {delay: 100}); // Types slower, like a user
|
3408 | ```
|
3409 |
|
3410 | > **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.
|
3411 |
|
3412 | #### keyboard.up(key)
|
3413 | - `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
|
3414 | - returns: <[Promise]>
|
3415 |
|
3416 | Dispatches a `keyup` event.
|
3417 |
|
3418 | ### class: Mouse
|
3419 |
|
3420 | The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.
|
3421 |
|
3422 | Every `page` object has its own Mouse, accessible with [`page.mouse`](#pagemouse).
|
3423 |
|
3424 | ```js
|
3425 | // Using ‘page.mouse’ to trace a 100x100 square.
|
3426 | await page.mouse.move(0, 0);
|
3427 | await page.mouse.down();
|
3428 | await page.mouse.move(0, 100);
|
3429 | await page.mouse.move(100, 100);
|
3430 | await page.mouse.move(100, 0);
|
3431 | await page.mouse.move(0, 0);
|
3432 | await page.mouse.up();
|
3433 | ```
|
3434 |
|
3435 |
|
3436 | - [mouse.click(x, y[, options])](#mouseclickx-y-options)
|
3437 | - [mouse.dblclick(x, y[, options])](#mousedblclickx-y-options)
|
3438 | - [mouse.down([options])](#mousedownoptions)
|
3439 | - [mouse.move(x, y[, options])](#mousemovex-y-options)
|
3440 | - [mouse.up([options])](#mouseupoptions)
|
3441 |
|
3442 |
|
3443 | #### mouse.click(x, y[, options])
|
3444 | - `x` <[number]>
|
3445 | - `y` <[number]>
|
3446 | - `options` <[Object]>
|
3447 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
3448 | - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
|
3449 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
3450 | - returns: <[Promise]>
|
3451 |
|
3452 | Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).
|
3453 |
|
3454 | #### mouse.dblclick(x, y[, options])
|
3455 | - `x` <[number]>
|
3456 | - `y` <[number]>
|
3457 | - `options` <[Object]>
|
3458 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
3459 | - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
|
3460 | - returns: <[Promise]>
|
3461 |
|
3462 | Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions), [`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).
|
3463 |
|
3464 | #### mouse.down([options])
|
3465 | - `options` <[Object]>
|
3466 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
3467 | - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
|
3468 | - returns: <[Promise]>
|
3469 |
|
3470 | Dispatches a `mousedown` event.
|
3471 |
|
3472 | #### mouse.move(x, y[, options])
|
3473 | - `x` <[number]>
|
3474 | - `y` <[number]>
|
3475 | - `options` <[Object]>
|
3476 | - `steps` <[number]> defaults to 1. Sends intermediate `mousemove` events.
|
3477 | - returns: <[Promise]>
|
3478 |
|
3479 | Dispatches a `mousemove` event.
|
3480 |
|
3481 | #### mouse.up([options])
|
3482 | - `options` <[Object]>
|
3483 | - `button` <"left"|"right"|"middle"> Defaults to `left`.
|
3484 | - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
|
3485 | - returns: <[Promise]>
|
3486 |
|
3487 | Dispatches a `mouseup` event.
|
3488 |
|
3489 |
|
3490 | ### class: Request
|
3491 |
|
3492 | Whenever the page sends a request, such as for a network resource, the following events are emitted by playwright's page:
|
3493 | - [`'request'`](#event-request) emitted when the request is issued by the page.
|
3494 | - [`'response'`](#event-response) emitted when/if the response is received for the request.
|
3495 | - [`'requestfinished'`](#event-requestfinished) emitted when the response body is downloaded and the request is complete.
|
3496 |
|
3497 | If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event), the [`'requestfailed'`](#event-requestfailed) event is emitted.
|
3498 |
|
3499 | > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with `'requestfinished'` event.
|
3500 |
|
3501 | If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new request is issued to a redirected url.
|
3502 |
|
3503 |
|
3504 | - [request.failure()](#requestfailure)
|
3505 | - [request.frame()](#requestframe)
|
3506 | - [request.headers()](#requestheaders)
|
3507 | - [request.isNavigationRequest()](#requestisnavigationrequest)
|
3508 | - [request.method()](#requestmethod)
|
3509 | - [request.postData()](#requestpostdata)
|
3510 | - [request.postDataBuffer()](#requestpostdatabuffer)
|
3511 | - [request.postDataJSON()](#requestpostdatajson)
|
3512 | - [request.redirectedFrom()](#requestredirectedfrom)
|
3513 | - [request.redirectedTo()](#requestredirectedto)
|
3514 | - [request.resourceType()](#requestresourcetype)
|
3515 | - [request.response()](#requestresponse)
|
3516 | - [request.url()](#requesturl)
|
3517 |
|
3518 |
|
3519 | #### request.failure()
|
3520 | - returns: <?[Object]> Object describing request failure, if any
|
3521 | - `errorText` <[string]> Human-readable error message, e.g. `'net::ERR_FAILED'`.
|
3522 |
|
3523 | The method returns `null` unless this request has failed, as reported by
|
3524 | `requestfailed` event.
|
3525 |
|
3526 | Example of logging of all the failed requests:
|
3527 |
|
3528 | ```js
|
3529 | page.on('requestfailed', request => {
|
3530 | console.log(request.url() + ' ' + request.failure().errorText);
|
3531 | });
|
3532 | ```
|
3533 |
|
3534 | #### request.frame()
|
3535 | - returns: <[Frame]> A [Frame] that initiated this request.
|
3536 |
|
3537 | #### request.headers()
|
3538 | - returns: <[Object]<[string], [string]>> An object with HTTP headers associated with the request. All header names are lower-case.
|
3539 |
|
3540 | #### request.isNavigationRequest()
|
3541 | - returns: <[boolean]>
|
3542 |
|
3543 | Whether this request is driving frame's navigation.
|
3544 |
|
3545 | #### request.method()
|
3546 | - returns: <[string]> Request's method (GET, POST, etc.)
|
3547 |
|
3548 | #### request.postData()
|
3549 | - returns: <?[string]> Request's post body, if any.
|
3550 |
|
3551 | #### request.postDataBuffer()
|
3552 | - returns: <?[Buffer]> Request's post body in a binary form, if any.
|
3553 |
|
3554 | #### request.postDataJSON()
|
3555 | - returns: <?[Object]> Parsed request's body for `form-urlencoded` and JSON as a fallback if any.
|
3556 |
|
3557 | When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned. Otherwise it will be parsed as JSON.
|
3558 |
|
3559 | #### request.redirectedFrom()
|
3560 | - returns: <?[Request]> Request that was redirected by the server to this one, if any.
|
3561 |
|
3562 | When the server responds with a redirect, Playwright creates a new [Request] object. The two requests are connected by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
|
3563 |
|
3564 | For example, if the website `http://example.com` redirects to `https://example.com`:
|
3565 | ```js
|
3566 | const response = await page.goto('http://example.com');
|
3567 | console.log(response.request().redirectedFrom().url()); // 'http://example.com'
|
3568 | ```
|
3569 |
|
3570 | If the website `https://google.com` has no redirects:
|
3571 | ```js
|
3572 | const response = await page.goto('https://google.com');
|
3573 | console.log(response.request().redirectedFrom()); // null
|
3574 | ```
|
3575 |
|
3576 | #### request.redirectedTo()
|
3577 | - returns: <?[Request]> New request issued by the browser if the server responded with redirect.
|
3578 |
|
3579 | This method is the opposite of [request.redirectedFrom()](#requestredirectedfrom):
|
3580 | ```js
|
3581 | console.log(request.redirectedFrom().redirectedTo() === request); // true
|
3582 | ```
|
3583 |
|
3584 | #### request.resourceType()
|
3585 | - returns: <[string]>
|
3586 |
|
3587 | Contains the request's resource type as it was perceived by the rendering engine.
|
3588 | ResourceType will be one of the following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`, `websocket`, `manifest`, `other`.
|
3589 |
|
3590 | #### request.response()
|
3591 | - returns: <[Promise]<?[Response]>> A matching [Response] object, or `null` if the response was not received due to error.
|
3592 |
|
3593 | #### request.url()
|
3594 | - returns: <[string]> URL of the request.
|
3595 |
|
3596 | ### class: Response
|
3597 |
|
3598 | [Response] class represents responses which are received by page.
|
3599 |
|
3600 |
|
3601 | - [response.body()](#responsebody)
|
3602 | - [response.finished()](#responsefinished)
|
3603 | - [response.frame()](#responseframe)
|
3604 | - [response.headers()](#responseheaders)
|
3605 | - [response.json()](#responsejson)
|
3606 | - [response.ok()](#responseok)
|
3607 | - [response.request()](#responserequest)
|
3608 | - [response.status()](#responsestatus)
|
3609 | - [response.statusText()](#responsestatustext)
|
3610 | - [response.text()](#responsetext)
|
3611 | - [response.url()](#responseurl)
|
3612 |
|
3613 |
|
3614 | #### response.body()
|
3615 | - returns: <[Promise]<[Buffer]>> Promise which resolves to a buffer with response body.
|
3616 |
|
3617 | #### response.finished()
|
3618 | - returns: <[Promise]<?[Error]>> Waits for this response to finish, returns failure error if request failed.
|
3619 |
|
3620 | #### response.frame()
|
3621 | - returns: <[Frame]> A [Frame] that initiated this response.
|
3622 |
|
3623 | #### response.headers()
|
3624 | - returns: <[Object]<[string], [string]>> An object with HTTP headers associated with the response. All header names are lower-case.
|
3625 |
|
3626 | #### response.json()
|
3627 | - returns: <[Promise]<[Object]>> Promise which resolves to a JSON representation of response body.
|
3628 |
|
3629 | This method will throw if the response body is not parsable via `JSON.parse`.
|
3630 |
|
3631 | #### response.ok()
|
3632 | - returns: <[boolean]>
|
3633 |
|
3634 | Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
|
3635 |
|
3636 | #### response.request()
|
3637 | - returns: <[Request]> A matching [Request] object.
|
3638 |
|
3639 | #### response.status()
|
3640 | - returns: <[number]>
|
3641 |
|
3642 | Contains the status code of the response (e.g., 200 for a success).
|
3643 |
|
3644 | #### response.statusText()
|
3645 | - returns: <[string]>
|
3646 |
|
3647 | Contains the status text of the response (e.g. usually an "OK" for a success).
|
3648 |
|
3649 | #### response.text()
|
3650 | - returns: <[Promise]<[string]>> Promise which resolves to a text representation of response body.
|
3651 |
|
3652 | #### response.url()
|
3653 | - returns: <[string]>
|
3654 |
|
3655 | Contains the URL of the response.
|
3656 |
|
3657 | ### class: Selectors
|
3658 |
|
3659 | Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more information.
|
3660 |
|
3661 |
|
3662 | - [selectors.register(name, script[, options])](#selectorsregistername-script-options)
|
3663 |
|
3664 |
|
3665 | #### selectors.register(name, script[, options])
|
3666 | - `name` <[string]> Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only contain `[a-zA-Z0-9_]` characters.
|
3667 | - `script` <[function]|[string]|[Object]> Script that evaluates to a selector engine instance.
|
3668 | - `path` <[string]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
3669 | - `content` <[string]> Raw script content.
|
3670 | - `options` <[Object]>
|
3671 | - `contentScript` <[boolean]> Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content script is not guaranteed when this engine is used together with other registered engines.
|
3672 | - returns: <[Promise]>
|
3673 |
|
3674 | An example of registering selector engine that queries elements based on a tag name:
|
3675 | ```js
|
3676 | const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
|
3677 |
|
3678 | (async () => {
|
3679 | // Must be a function that evaluates to a selector engine instance.
|
3680 | const createTagNameEngine = () => ({
|
3681 | // Creates a selector that matches given target when queried at the root.
|
3682 | // Can return undefined if unable to create one.
|
3683 | create(root, target) {
|
3684 | return root.querySelector(target.tagName) === target ? target.tagName : undefined;
|
3685 | },
|
3686 |
|
3687 | // Returns the first element matching given selector in the root's subtree.
|
3688 | query(root, selector) {
|
3689 | return root.querySelector(selector);
|
3690 | },
|
3691 |
|
3692 | // Returns all elements matching given selector in the root's subtree.
|
3693 | queryAll(root, selector) {
|
3694 | return Array.from(root.querySelectorAll(selector));
|
3695 | }
|
3696 | });
|
3697 |
|
3698 | // Register the engine. Selectors will be prefixed with "tag=".
|
3699 | await selectors.register('tag', createTagNameEngine);
|
3700 |
|
3701 | const browser = await firefox.launch();
|
3702 | const page = await browser.newPage();
|
3703 | await page.setContent(`<div><button>Click me</button></div>`);
|
3704 |
|
3705 | // Use the selector prefixed with its name.
|
3706 | const button = await page.$('tag=button');
|
3707 | // Combine it with other selector engines.
|
3708 | await page.click('tag=div >> text="Click me"');
|
3709 | // Can use it in any methods supporting selectors.
|
3710 | const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
|
3711 |
|
3712 | await browser.close();
|
3713 | })();
|
3714 | ```
|
3715 |
|
3716 |
|
3717 | ### class: Route
|
3718 |
|
3719 | Whenever a network route is set up with [page.route(url, handler)](#pagerouteurl-handler) or [browserContext.route(url, handler)](#browsercontextrouteurl-handler), the `Route` object allows to handle the route.
|
3720 |
|
3721 |
|
3722 | - [route.abort([errorCode])](#routeaborterrorcode)
|
3723 | - [route.continue([overrides])](#routecontinueoverrides)
|
3724 | - [route.fulfill(response)](#routefulfillresponse)
|
3725 | - [route.request()](#routerequest)
|
3726 |
|
3727 |
|
3728 | #### route.abort([errorCode])
|
3729 | - `errorCode` <[string]> Optional error code. Defaults to `failed`, could be
|
3730 | one of the following:
|
3731 | - `'aborted'` - An operation was aborted (due to user action)
|
3732 | - `'accessdenied'` - Permission to access a resource, other than the network, was denied
|
3733 | - `'addressunreachable'` - The IP address is unreachable. This usually means
|
3734 | that there is no route to the specified host or network.
|
3735 | - `'blockedbyclient'` - The client chose to block the request.
|
3736 | - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
|
3737 | - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
|
3738 | - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).
|
3739 | - `'connectionfailed'` - A connection attempt failed.
|
3740 | - `'connectionrefused'` - A connection attempt was refused.
|
3741 | - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).
|
3742 | - `'internetdisconnected'` - The Internet connection has been lost.
|
3743 | - `'namenotresolved'` - The host name could not be resolved.
|
3744 | - `'timedout'` - An operation timed out.
|
3745 | - `'failed'` - A generic failure occurred.
|
3746 | - returns: <[Promise]>
|
3747 |
|
3748 | Aborts the route's request.
|
3749 |
|
3750 | #### route.continue([overrides])
|
3751 | - `overrides` <[Object]> Optional request overrides, which can be one of the following:
|
3752 | - `method` <[string]> If set changes the request method (e.g. GET or POST)
|
3753 | - `postData` <[string]|[Buffer]> If set changes the post data of request
|
3754 | - `headers` <[Object]<[string], [string]>> If set changes the request HTTP headers. Header values will be converted to a string.
|
3755 | - returns: <[Promise]>
|
3756 |
|
3757 | Continues route's request with optional overrides.
|
3758 |
|
3759 | ```js
|
3760 | await page.route('**/*', (route, request) => {
|
3761 | // Override headers
|
3762 | const headers = Object.assign({}, request.headers(), {
|
3763 | foo: 'bar', // set "foo" header
|
3764 | origin: undefined, // remove "origin" header
|
3765 | });
|
3766 | route.continue({headers});
|
3767 | });
|
3768 | ```
|
3769 |
|
3770 | #### route.fulfill(response)
|
3771 | - `response` <[Object]> Response that will fulfill this route's request.
|
3772 | - `status` <[number]> Response status code, defaults to `200`.
|
3773 | - `headers` <[Object]<[string], [string]>> Optional response headers. Header values will be converted to a string.
|
3774 | - `contentType` <[string]> If set, equals to setting `Content-Type` response header.
|
3775 | - `body` <[string]|[Buffer]> Optional response body.
|
3776 | - `path` <[string]> Optional file path to respond with. The content type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
|
3777 | - returns: <[Promise]>
|
3778 |
|
3779 | Fulfills route's request with given response.
|
3780 |
|
3781 | An example of fulfilling all requests with 404 responses:
|
3782 |
|
3783 | ```js
|
3784 | await page.route('**/*', route => {
|
3785 | route.fulfill({
|
3786 | status: 404,
|
3787 | contentType: 'text/plain',
|
3788 | body: 'Not Found!'
|
3789 | });
|
3790 | });
|
3791 | ```
|
3792 |
|
3793 | An example of serving static file:
|
3794 |
|
3795 | ```js
|
3796 | await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));
|
3797 | ```
|
3798 |
|
3799 | #### route.request()
|
3800 | - returns: <[Request]> A request to be routed.
|
3801 |
|
3802 |
|
3803 | ### class: TimeoutError
|
3804 |
|
3805 | * extends: [Error]
|
3806 |
|
3807 | TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g. [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) or [browserType.launch([options])](#browsertypelaunchoptions).
|
3808 |
|
3809 | ### class: Accessibility
|
3810 |
|
3811 | The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or [switches](https://en.wikipedia.org/wiki/Switch_access).
|
3812 |
|
3813 | Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.
|
3814 |
|
3815 | Blink - Chromium's rendering engine - has a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives users
|
3816 | access to the Blink Accessibility Tree.
|
3817 |
|
3818 | Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Playwright tries to approximate this filtering, exposing only the "interesting" nodes of the tree.
|
3819 |
|
3820 |
|
3821 | - [accessibility.snapshot([options])](#accessibilitysnapshotoptions)
|
3822 |
|
3823 |
|
3824 | #### accessibility.snapshot([options])
|
3825 | - `options` <[Object]>
|
3826 | - `interestingOnly` <[boolean]> Prune uninteresting nodes from the tree. Defaults to `true`.
|
3827 | - `root` <[ElementHandle]> The root DOM element for the snapshot. Defaults to the whole page.
|
3828 | - returns: <[Promise]<?[Object]>> An [AXNode] object with the following properties:
|
3829 | - `role` <[string]> The [role](https://www.w3.org/TR/wai-aria/#usage_intro).
|
3830 | - `name` <[string]> A human readable name for the node.
|
3831 | - `value` <[string]|[number]> The current value of the node, if applicable.
|
3832 | - `description` <[string]> An additional human readable description of the node, if applicable.
|
3833 | - `keyshortcuts` <[string]> Keyboard shortcuts associated with this node, if applicable.
|
3834 | - `roledescription` <[string]> A human readable alternative to the role, if applicable.
|
3835 | - `valuetext` <[string]> A description of the current value, if applicable.
|
3836 | - `disabled` <[boolean]> Whether the node is disabled, if applicable.
|
3837 | - `expanded` <[boolean]> Whether the node is expanded or collapsed, if applicable.
|
3838 | - `focused` <[boolean]> Whether the node is focused, if applicable.
|
3839 | - `modal` <[boolean]> Whether the node is [modal](https://en.wikipedia.org/wiki/Modal_window), if applicable.
|
3840 | - `multiline` <[boolean]> Whether the node text input supports multiline, if applicable.
|
3841 | - `multiselectable` <[boolean]> Whether more than one child can be selected, if applicable.
|
3842 | - `readonly` <[boolean]> Whether the node is read only, if applicable.
|
3843 | - `required` <[boolean]> Whether the node is required, if applicable.
|
3844 | - `selected` <[boolean]> Whether the node is selected in its parent node, if applicable.
|
3845 | - `checked` <[boolean]|"mixed"> Whether the checkbox is checked, or "mixed", if applicable.
|
3846 | - `pressed` <[boolean]|"mixed"> Whether the toggle button is checked, or "mixed", if applicable.
|
3847 | - `level` <[number]> The level of a heading, if applicable.
|
3848 | - `valuemin` <[number]> The minimum value in a node, if applicable.
|
3849 | - `valuemax` <[number]> The maximum value in a node, if applicable.
|
3850 | - `autocomplete` <[string]> What kind of autocomplete is supported by a control, if applicable.
|
3851 | - `haspopup` <[string]> What kind of popup is currently being shown for a node, if applicable.
|
3852 | - `invalid` <[string]> Whether and in what way this node's value is invalid, if applicable.
|
3853 | - `orientation` <[string]> Whether the node is oriented horizontally or vertically, if applicable.
|
3854 | - `children` <[Array]<[Object]>> Child [AXNode]s of this node, if any, if applicable.
|
3855 |
|
3856 | Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.
|
3857 |
|
3858 | > **NOTE** The Chromium accessibility tree contains nodes that go unused on most platforms and by
|
3859 | most screen readers. Playwright will discard them as well for an easier to process tree,
|
3860 | unless `interestingOnly` is set to `false`.
|
3861 |
|
3862 | An example of dumping the entire accessibility tree:
|
3863 | ```js
|
3864 | const snapshot = await page.accessibility.snapshot();
|
3865 | console.log(snapshot);
|
3866 | ```
|
3867 |
|
3868 | An example of logging the focused node's name:
|
3869 | ```js
|
3870 | const snapshot = await page.accessibility.snapshot();
|
3871 | const node = findFocusedNode(snapshot);
|
3872 | console.log(node && node.name);
|
3873 |
|
3874 | function findFocusedNode(node) {
|
3875 | if (node.focused)
|
3876 | return node;
|
3877 | for (const child of node.children || []) {
|
3878 | const foundNode = findFocusedNode(child);
|
3879 | return foundNode;
|
3880 | }
|
3881 | return null;
|
3882 | }
|
3883 | ```
|
3884 |
|
3885 | ### class: Worker
|
3886 |
|
3887 | The Worker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
|
3888 | `worker` event is emitted on the page object to signal a worker creation.
|
3889 | `close` event is emitted on the worker object when the worker is gone.
|
3890 |
|
3891 | ```js
|
3892 | page.on('worker', worker => {
|
3893 | console.log('Worker created: ' + worker.url());
|
3894 | worker.on('close', worker => console.log('Worker destroyed: ' + worker.url()));
|
3895 | });
|
3896 |
|
3897 | console.log('Current workers:');
|
3898 | for (const worker of page.workers())
|
3899 | console.log(' ' + worker.url());
|
3900 | ```
|
3901 |
|
3902 |
|
3903 | - [event: 'close'](#event-close-2)
|
3904 | - [worker.evaluate(pageFunction[, arg])](#workerevaluatepagefunction-arg)
|
3905 | - [worker.evaluateHandle(pageFunction[, arg])](#workerevaluatehandlepagefunction-arg)
|
3906 | - [worker.url()](#workerurl)
|
3907 |
|
3908 |
|
3909 | #### event: 'close'
|
3910 | - <[Worker]>
|
3911 |
|
3912 | Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is terminated.
|
3913 |
|
3914 | #### worker.evaluate(pageFunction[, arg])
|
3915 | - `pageFunction` <[function]|[string]> Function to be evaluated in the worker context
|
3916 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
3917 | - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
|
3918 |
|
3919 | If the function passed to the `worker.evaluate` returns a [Promise], then `worker.evaluate` would wait for the promise to resolve and return its value.
|
3920 |
|
3921 | If the function passed to the `worker.evaluate` returns a non-[Serializable] value, then `worker.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.
|
3922 |
|
3923 | #### worker.evaluateHandle(pageFunction[, arg])
|
3924 | - `pageFunction` <[function]|[string]> Function to be evaluated in the page context
|
3925 | - `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
|
3926 | - returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
|
3927 |
|
3928 | The only difference between `worker.evaluate` and `worker.evaluateHandle` is that `worker.evaluateHandle` returns in-page object (JSHandle).
|
3929 |
|
3930 | If the function passed to the `worker.evaluateHandle` returns a [Promise], then `worker.evaluateHandle` would wait for the promise to resolve and return its value.
|
3931 |
|
3932 | #### worker.url()
|
3933 | - returns: <[string]>
|
3934 |
|
3935 |
|
3936 | ### class: BrowserServer
|
3937 |
|
3938 |
|
3939 | - [event: 'close'](#event-close-3)
|
3940 | - [browserServer.close()](#browserserverclose)
|
3941 | - [browserServer.kill()](#browserserverkill)
|
3942 | - [browserServer.process()](#browserserverprocess)
|
3943 | - [browserServer.wsEndpoint()](#browserserverwsendpoint)
|
3944 |
|
3945 |
|
3946 | #### event: 'close'
|
3947 |
|
3948 | Emitted when the browser server closes.
|
3949 |
|
3950 | #### browserServer.close()
|
3951 | - returns: <[Promise]>
|
3952 |
|
3953 | Closes the browser gracefully and makes sure the process is terminated.
|
3954 |
|
3955 | #### browserServer.kill()
|
3956 | - returns: <[Promise]>
|
3957 |
|
3958 | Kills the browser process and waits for the process to exit.
|
3959 |
|
3960 | #### browserServer.process()
|
3961 | - returns: <[ChildProcess]> Spawned browser application process.
|
3962 |
|
3963 | #### browserServer.wsEndpoint()
|
3964 | - returns: <[string]> Browser websocket url.
|
3965 |
|
3966 | Browser websocket endpoint which can be used as an argument to [browserType.connect(options)](#browsertypeconnectoptions) to establish connection to the browser.
|
3967 |
|
3968 | ### class: BrowserType
|
3969 |
|
3970 | BrowserType provides methods to launch a specific browser instance or connect to an existing one.
|
3971 | The following is a typical example of using Playwright to drive automation:
|
3972 | ```js
|
3973 | const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
|
3974 |
|
3975 | (async () => {
|
3976 | const browser = await chromium.launch();
|
3977 | const page = await browser.newPage();
|
3978 | await page.goto('https://example.com');
|
3979 | // other actions...
|
3980 | await browser.close();
|
3981 | })();
|
3982 | ```
|
3983 |
|
3984 |
|
3985 | - [browserType.connect(options)](#browsertypeconnectoptions)
|
3986 | - [browserType.executablePath()](#browsertypeexecutablepath)
|
3987 | - [browserType.launch([options])](#browsertypelaunchoptions)
|
3988 | - [browserType.launchPersistentContext(userDataDir, [options])](#browsertypelaunchpersistentcontextuserdatadir-options)
|
3989 | - [browserType.launchServer([options])](#browsertypelaunchserveroptions)
|
3990 | - [browserType.name()](#browsertypename)
|
3991 |
|
3992 |
|
3993 | #### browserType.connect(options)
|
3994 | - `options` <[Object]>
|
3995 | - `wsEndpoint` <[string]> A browser websocket endpoint to connect to. **required**
|
3996 | - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.
|
3997 | - `logger` <[Logger]> Logger sink for Playwright logging.
|
3998 | - `timeout` <[number]> Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
|
3999 | - returns: <[Promise]<[Browser]>>
|
4000 |
|
4001 | This methods attaches Playwright to an existing browser instance.
|
4002 |
|
4003 | #### browserType.executablePath()
|
4004 | - returns: <[string]> A path where Playwright expects to find a bundled browser executable.
|
4005 |
|
4006 | #### browserType.launch([options])
|
4007 | - `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
|
4008 | - `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
|
4009 | - `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk.
|
4010 | - `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
|
4011 | - `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
|
4012 | - `proxy` <[Object]> Network proxy settings.
|
4013 | - `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
|
4014 | - `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
|
4015 | - `username` <[string]> Optional username to use if HTTP proxy requires authentication.
|
4016 | - `password` <[string]> Optional password to use if HTTP proxy requires authentication.
|
4017 | - `downloadsPath` <[string]> If specified, accepted downloads are downloaded into this folder. Otherwise, temporary folder is created and is deleted when browser is closed.
|
4018 | - `chromiumSandbox` <[boolean]> Enable Chromium sandboxing. Defaults to `true`.
|
4019 | - `firefoxUserPrefs` <[Object]> Firefox user preferences. Learn more about the Firefox user preferences at [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
|
4020 | - `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
|
4021 | - `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
|
4022 | - `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
|
4023 | - `logger` <[Logger]> Logger sink for Playwright logging.
|
4024 | - `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
|
4025 | - `env` <[Object]<[string], [string]|[number]|[boolean]>> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
|
4026 | - `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
|
4027 | - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
|
4028 | - returns: <[Promise]<[Browser]>> Promise which resolves to browser instance.
|
4029 |
|
4030 |
|
4031 | You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
|
4032 | ```js
|
4033 | const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
|
4034 | ignoreDefaultArgs: ['--mute-audio']
|
4035 | });
|
4036 | ```
|
4037 |
|
4038 | > **Chromium-only** Playwright can also be used to control the Chrome browser, 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.
|
4039 | >
|
4040 | > 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.
|
4041 | >
|
4042 | > In [browserType.launch([options])](#browsertypelaunchoptions) above, any mention of Chromium also applies to Chrome.
|
4043 | >
|
4044 | > See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the 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.
|
4045 |
|
4046 | #### browserType.launchPersistentContext(userDataDir, [options])
|
4047 | - `userDataDir` <[string]> 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) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile).
|
4048 | - `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
|
4049 | - `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
|
4050 | - `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
|
4051 | - `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
|
4052 | - `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use any of the default arguments. If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`.
|
4053 | - `proxy` <[Object]> Network proxy settings.
|
4054 | - `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
|
4055 | - `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
|
4056 | - `username` <[string]> Optional username to use if HTTP proxy requires authentication.
|
4057 | - `password` <[string]> Optional password to use if HTTP proxy requires authentication.
|
4058 | - `acceptDownloads` <[boolean]> Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
|
4059 | - `downloadsPath` <[string]> If specified, accepted downloads are downloaded into this folder. Otherwise, temporary folder is created and is deleted when browser is closed.
|
4060 | - `chromiumSandbox` <[boolean]> Enable Chromium sandboxing. Defaults to `true`.
|
4061 | - `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
|
4062 | - `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
|
4063 | - `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
|
4064 | - `logger` <[Logger]> Logger sink for Playwright logging.
|
4065 | - `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
|
4066 | - `env` <[Object]<[string], [string]|[number]|[boolean]>> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
|
4067 | - `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
|
4068 | - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.
|
4069 | - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
|
4070 | - `bypassCSP` <[boolean]> Toggles bypassing page's Content-Security-Policy.
|
4071 | - `viewport` <?[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
|
4072 | - `width` <[number]> page width in pixels.
|
4073 | - `height` <[number]> page height in pixels.
|
4074 | - `userAgent` <[string]> Specific user agent to use in this context.
|
4075 | - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.
|
4076 | - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported in Firefox.
|
4077 | - `hasTouch` <[boolean]> Specifies if viewport supports touch events. Defaults to false.
|
4078 | - `javaScriptEnabled` <[boolean]> Whether or not to enable JavaScript in the context. Defaults to true.
|
4079 | - `timezoneId` <[string]> Changes the timezone of the context. See [ICU’s `metaZones.txt`](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
|
4080 | - `geolocation` <[Object]>
|
4081 | - `latitude` <[number]> Latitude between -90 and 90.
|
4082 | - `longitude` <[number]> Longitude between -180 and 180.
|
4083 | - `accuracy` <[number]> Optional non-negative accuracy value. Defaults to `0`.
|
4084 | - `locale` <[string]> Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language` request header value as well as number and date formatting rules.
|
4085 | - `permissions` <[Array]<[string]>> A list of permissions to grant to all pages in this context. See [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) for more details.
|
4086 | - `extraHTTPHeaders` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
|
4087 | - `offline` <[boolean]> Whether to emulate network being offline. Defaults to `false`.
|
4088 | - `httpCredentials` <[Object]> Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
|
4089 | - `username` <[string]>
|
4090 | - `password` <[string]>
|
4091 | - `colorScheme` <"light"|"dark"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(options)](#pageemulatemediaoptions) for more details. Defaults to '`light`'.
|
4092 | - returns: <[Promise]<[BrowserContext]>> Promise that resolves to the persistent browser context instance.
|
4093 |
|
4094 | Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this context will automatically close the browser.
|
4095 |
|
4096 | #### browserType.launchServer([options])
|
4097 | - `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
|
4098 | - `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
|
4099 | - `port` <[number]> Port to use for the web socket. Defaults to 0 that picks any available port.
|
4100 | - `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
|
4101 | - `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
|
4102 | - `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use any of the default arguments. If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`.
|
4103 | - `proxy` <[Object]> Network proxy settings.
|
4104 | - `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
|
4105 | - `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
|
4106 | - `username` <[string]> Optional username to use if HTTP proxy requires authentication.
|
4107 | - `password` <[string]> Optional password to use if HTTP proxy requires authentication.
|
4108 | - `downloadsPath` <[string]> If specified, accepted downloads are downloaded into this folder. Otherwise, temporary folder is created and is deleted when browser is closed.
|
4109 | - `chromiumSandbox` <[boolean]> Enable Chromium sandboxing. Defaults to `true`.
|
4110 | - `firefoxUserPrefs` <[Object]> Firefox user preferences. Learn more about the Firefox user preferences at [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
|
4111 | - `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
|
4112 | - `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
|
4113 | - `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
|
4114 | - `logger` <[Logger]> Logger sink for Playwright logging.
|
4115 | - `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
|
4116 | - `env` <[Object]<[string], [string]|[number]|[boolean]>> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
|
4117 | - `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
|
4118 | - returns: <[Promise]<[BrowserServer]>> Promise which resolves to the browser app instance.
|
4119 |
|
4120 | Launches browser server that client can connect to. An example of launching a browser executable and connecting to it later:
|
4121 |
|
4122 | ```js
|
4123 | const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
|
4124 |
|
4125 | (async () => {
|
4126 | const browserServer = await chromium.launchServer();
|
4127 | const wsEndpoint = browserServer.wsEndpoint();
|
4128 | // Use web socket endpoint later to establish a connection.
|
4129 | const browser = await chromium.connect({ wsEndpoint });
|
4130 | // Close browser instance.
|
4131 | await browserServer.close();
|
4132 | })();
|
4133 | ```
|
4134 |
|
4135 |
|
4136 | #### browserType.name()
|
4137 | - returns: <[string]>
|
4138 |
|
4139 | Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
|
4140 |
|
4141 | ### class: Logger
|
4142 |
|
4143 | Playwright generates a lot of logs and they are accessible via the pluggable logger sink.
|
4144 |
|
4145 | ```js
|
4146 | const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
|
4147 |
|
4148 | (async () => {
|
4149 | const browser = await chromium.launch({
|
4150 | logger: {
|
4151 | isEnabled: (name, severity) => name === 'browser',
|
4152 | log: (name, severity, message, args) => console.log(`${name} ${message}`)
|
4153 | }
|
4154 | });
|
4155 | ...
|
4156 | })();
|
4157 | ```
|
4158 |
|
4159 |
|
4160 | - [logger.isEnabled(name, severity)](#loggerisenabledname-severity)
|
4161 | - [logger.log(name, severity, message, args, hints)](#loggerlogname-severity-message-args-hints)
|
4162 |
|
4163 |
|
4164 | #### logger.isEnabled(name, severity)
|
4165 | - `name` <[string]> logger name
|
4166 | - `severity` <"verbose"|"info"|"warning"|"error">
|
4167 | - returns: <[boolean]>
|
4168 |
|
4169 | Determines whether sink is interested in the logger with the given name and severity.
|
4170 |
|
4171 | #### logger.log(name, severity, message, args, hints)
|
4172 | - `name` <[string]> logger name
|
4173 | - `severity` <"verbose"|"info"|"warning"|"error">
|
4174 | - `message` <[string]|[Error]> log message format
|
4175 | - `args` <[Array]<[Object]>> message arguments
|
4176 | - `hints` <[Object]> optional formatting hints
|
4177 | - `color` <[string]> preferred logger color
|
4178 |
|
4179 | ### class: ChromiumBrowser
|
4180 |
|
4181 | * extends: [Browser]
|
4182 |
|
4183 | Chromium-specific features including Tracing, service worker support, etc.
|
4184 | You can use [`chromiumBrowser.startTracing`](#chromiumbrowserstarttracingpage-options) and [`chromiumBrowser.stopTracing`](#chromiumbrowserstoptracing) to create a trace file which can be opened in Chrome DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/).
|
4185 |
|
4186 | ```js
|
4187 | await browser.startTracing(page, {path: 'trace.json'});
|
4188 | await page.goto('https://www.google.com');
|
4189 | await browser.stopTracing();
|
4190 | ```
|
4191 |
|
4192 |
|
4193 | - [chromiumBrowser.newBrowserCDPSession()](#chromiumbrowsernewbrowsercdpsession)
|
4194 | - [chromiumBrowser.startTracing([page, options])](#chromiumbrowserstarttracingpage-options)
|
4195 | - [chromiumBrowser.stopTracing()](#chromiumbrowserstoptracing)
|
4196 |
|
4197 |
|
4198 | - [event: 'disconnected'](#event-disconnected)
|
4199 | - [browser.close()](#browserclose)
|
4200 | - [browser.contexts()](#browsercontexts)
|
4201 | - [browser.isConnected()](#browserisconnected)
|
4202 | - [browser.newContext([options])](#browsernewcontextoptions)
|
4203 | - [browser.newPage([options])](#browsernewpageoptions)
|
4204 | - [browser.version()](#browserversion)
|
4205 |
|
4206 |
|
4207 | #### chromiumBrowser.newBrowserCDPSession()
|
4208 | - returns: <[Promise]<[CDPSession]>> Promise that resolves to the newly created browser
|
4209 | session.
|
4210 |
|
4211 | #### chromiumBrowser.startTracing([page, options])
|
4212 | - `page` <[Page]> Optional, if specified, tracing includes screenshots of the given page.
|
4213 | - `options` <[Object]>
|
4214 | - `path` <[string]> A path to write the trace file to.
|
4215 | - `screenshots` <[boolean]> captures screenshots in the trace.
|
4216 | - `categories` <[Array]<[string]>> specify custom categories to use instead of default.
|
4217 | - returns: <[Promise]>
|
4218 |
|
4219 | Only one trace can be active at a time per browser.
|
4220 |
|
4221 | #### chromiumBrowser.stopTracing()
|
4222 | - returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with trace data.
|
4223 |
|
4224 | ### class: ChromiumBrowserContext
|
4225 |
|
4226 | * extends: [BrowserContext]
|
4227 |
|
4228 | Chromium-specific features including background pages, service worker support, etc.
|
4229 |
|
4230 | ```js
|
4231 | const backgroundPage = await context.waitForEvent('backgroundpage');
|
4232 | ```
|
4233 |
|
4234 |
|
4235 | - [event: 'backgroundpage'](#event-backgroundpage)
|
4236 | - [event: 'serviceworker'](#event-serviceworker)
|
4237 | - [chromiumBrowserContext.backgroundPages()](#chromiumbrowsercontextbackgroundpages)
|
4238 | - [chromiumBrowserContext.newCDPSession(page)](#chromiumbrowsercontextnewcdpsessionpage)
|
4239 | - [chromiumBrowserContext.serviceWorkers()](#chromiumbrowsercontextserviceworkers)
|
4240 |
|
4241 |
|
4242 | - [event: 'close'](#event-close)
|
4243 | - [event: 'page'](#event-page)
|
4244 | - [browserContext.addCookies(cookies)](#browsercontextaddcookiescookies)
|
4245 | - [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg)
|
4246 | - [browserContext.clearCookies()](#browsercontextclearcookies)
|
4247 | - [browserContext.clearPermissions()](#browsercontextclearpermissions)
|
4248 | - [browserContext.close()](#browsercontextclose)
|
4249 | - [browserContext.cookies([urls])](#browsercontextcookiesurls)
|
4250 | - [browserContext.exposeBinding(name, playwrightBinding)](#browsercontextexposebindingname-playwrightbinding)
|
4251 | - [browserContext.exposeFunction(name, playwrightFunction)](#browsercontextexposefunctionname-playwrightfunction)
|
4252 | - [browserContext.grantPermissions(permissions[][, options])](#browsercontextgrantpermissionspermissions-options)
|
4253 | - [browserContext.newPage()](#browsercontextnewpage)
|
4254 | - [browserContext.pages()](#browsercontextpages)
|
4255 | - [browserContext.route(url, handler)](#browsercontextrouteurl-handler)
|
4256 | - [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout)
|
4257 | - [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout)
|
4258 | - [browserContext.setExtraHTTPHeaders(headers)](#browsercontextsetextrahttpheadersheaders)
|
4259 | - [browserContext.setGeolocation(geolocation)](#browsercontextsetgeolocationgeolocation)
|
4260 | - [browserContext.setHTTPCredentials(httpCredentials)](#browsercontextsethttpcredentialshttpcredentials)
|
4261 | - [browserContext.setOffline(offline)](#browsercontextsetofflineoffline)
|
4262 | - [browserContext.unroute(url[, handler])](#browsercontextunrouteurl-handler)
|
4263 | - [browserContext.waitForEvent(event[, optionsOrPredicate])](#browsercontextwaitforeventevent-optionsorpredicate)
|
4264 |
|
4265 |
|
4266 | #### event: 'backgroundpage'
|
4267 | - <[Page]>
|
4268 |
|
4269 | Emitted when new background page is created in the context.
|
4270 |
|
4271 | > **NOTE** Only works with persistent context.
|
4272 |
|
4273 | #### event: 'serviceworker'
|
4274 | - <[Worker]>
|
4275 |
|
4276 | Emitted when new service worker is created in the context.
|
4277 |
|
4278 | #### chromiumBrowserContext.backgroundPages()
|
4279 | - returns: <[Array]<[Page]>> All existing background pages in the context.
|
4280 |
|
4281 | #### chromiumBrowserContext.newCDPSession(page)
|
4282 | - `page` <[Page]> Page to create new session for.
|
4283 | - returns: <[Promise]<[CDPSession]>> Promise that resolves to the newly created session.
|
4284 |
|
4285 | #### chromiumBrowserContext.serviceWorkers()
|
4286 | - returns: <[Array]<[Worker]>> All existing service workers in the context.
|
4287 |
|
4288 | ### class: ChromiumCoverage
|
4289 |
|
4290 | Coverage gathers information about parts of JavaScript and CSS that were used by the page.
|
4291 |
|
4292 | An example of using JavaScript coverage to produce Istambul report for page load:
|
4293 |
|
4294 | ```js
|
4295 | const { chromium } = require('playwright');
|
4296 | const v8toIstanbul = require('v8-to-istanbul');
|
4297 |
|
4298 | (async() => {
|
4299 | const browser = await chromium.launch();
|
4300 | const page = await browser.newPage();
|
4301 | await page.coverage.startJSCoverage();
|
4302 | await page.goto('https://chromium.org');
|
4303 | const coverage = await page.coverage.stopJSCoverage();
|
4304 | for (const entry of coverage) {
|
4305 | const converter = new v8toIstanbul('', 0, { source: entry.source });
|
4306 | await converter.load();
|
4307 | converter.applyCoverage(entry.functions);
|
4308 | console.log(JSON.stringify(converter.toIstanbul()));
|
4309 | }
|
4310 | await browser.close();
|
4311 | })();
|
4312 | ```
|
4313 |
|
4314 |
|
4315 | - [chromiumCoverage.startCSSCoverage([options])](#chromiumcoveragestartcsscoverageoptions)
|
4316 | - [chromiumCoverage.startJSCoverage([options])](#chromiumcoveragestartjscoverageoptions)
|
4317 | - [chromiumCoverage.stopCSSCoverage()](#chromiumcoveragestopcsscoverage)
|
4318 | - [chromiumCoverage.stopJSCoverage()](#chromiumcoveragestopjscoverage)
|
4319 |
|
4320 |
|
4321 | #### chromiumCoverage.startCSSCoverage([options])
|
4322 | - `options` <[Object]> Set of configurable options for coverage
|
4323 | - `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
|
4324 | - returns: <[Promise]> Promise that resolves when coverage is started
|
4325 |
|
4326 | #### chromiumCoverage.startJSCoverage([options])
|
4327 | - `options` <[Object]> Set of configurable options for coverage
|
4328 | - `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
|
4329 | - `reportAnonymousScripts` <[boolean]> Whether anonymous scripts generated by the page should be reported. Defaults to `false`.
|
4330 | - returns: <[Promise]> Promise that resolves when coverage is started
|
4331 |
|
4332 | > **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created on the page using `eval` or `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.
|
4333 |
|
4334 | #### chromiumCoverage.stopCSSCoverage()
|
4335 | - returns: <[Promise]<[Array]<[Object]>>> Promise that resolves to the array of coverage reports for all stylesheets
|
4336 | - `url` <[string]> StyleSheet URL
|
4337 | - `text` <[string]> StyleSheet content, if available.
|
4338 | - `ranges` <[Array]<[Object]>> StyleSheet ranges that were used. Ranges are sorted and non-overlapping.
|
4339 | - `start` <[number]> A start offset in text, inclusive
|
4340 | - `end` <[number]> An end offset in text, exclusive
|
4341 |
|
4342 | > **NOTE** CSS Coverage doesn't include dynamically injected style tags without sourceURLs.
|
4343 |
|
4344 | #### chromiumCoverage.stopJSCoverage()
|
4345 | - returns: <[Promise]<[Array]<[Object]>>> Promise that resolves to the array of coverage reports for all scripts
|
4346 | - `url` <[string]> Script URL
|
4347 | - `scriptId` <[string]> Script ID
|
4348 | - `source` <[string]> Script content, if applicable.
|
4349 | - `functions` <[Array]<[Object]>> V8-specific coverage format.
|
4350 | - `functionName` <[string]>
|
4351 | - `isBlockCoverage` <[boolean]>
|
4352 | - `ranges` <[Array]<[Object]>>
|
4353 | - `count` <[number]>
|
4354 | - `startOffset` <[number]>
|
4355 | - `endOffset` <[number]>
|
4356 |
|
4357 | > **NOTE** JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are
|
4358 | reported.
|
4359 |
|
4360 | ### class: CDPSession
|
4361 |
|
4362 | * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
|
4363 |
|
4364 | The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
|
4365 | - protocol methods can be called with `session.send` method.
|
4366 | - protocol events can be subscribed to with `session.on` method.
|
4367 |
|
4368 | Useful links:
|
4369 | - Documentation on DevTools Protocol can be found here: [DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/).
|
4370 | - Getting Started with DevTools Protocol: https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md
|
4371 |
|
4372 | ```js
|
4373 | const client = await page.context().newCDPSession(page);
|
4374 | await client.send('Animation.enable');
|
4375 | client.on('Animation.animationCreated', () => console.log('Animation created!'));
|
4376 | const response = await client.send('Animation.getPlaybackRate');
|
4377 | console.log('playback rate is ' + response.playbackRate);
|
4378 | await client.send('Animation.setPlaybackRate', {
|
4379 | playbackRate: response.playbackRate / 2
|
4380 | });
|
4381 | ```
|
4382 |
|
4383 |
|
4384 | - [cdpSession.detach()](#cdpsessiondetach)
|
4385 | - [cdpSession.send(method[, params])](#cdpsessionsendmethod-params)
|
4386 |
|
4387 |
|
4388 | #### cdpSession.detach()
|
4389 | - returns: <[Promise]>
|
4390 |
|
4391 | Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used
|
4392 | to send messages.
|
4393 |
|
4394 | #### cdpSession.send(method[, params])
|
4395 | - `method` <[string]> protocol method name
|
4396 | - `params` <[Object]> Optional method parameters
|
4397 | - returns: <[Promise]<[Object]>>
|
4398 |
|
4399 | ### class: FirefoxBrowser
|
4400 |
|
4401 | * extends: [Browser]
|
4402 |
|
4403 | Firefox browser instance does not expose Firefox-specific features.
|
4404 |
|
4405 |
|
4406 | - [event: 'disconnected'](#event-disconnected)
|
4407 | - [browser.close()](#browserclose)
|
4408 | - [browser.contexts()](#browsercontexts)
|
4409 | - [browser.isConnected()](#browserisconnected)
|
4410 | - [browser.newContext([options])](#browsernewcontextoptions)
|
4411 | - [browser.newPage([options])](#browsernewpageoptions)
|
4412 | - [browser.version()](#browserversion)
|
4413 |
|
4414 |
|
4415 | ### class: WebKitBrowser
|
4416 |
|
4417 | * extends: [Browser]
|
4418 |
|
4419 | WebKit browser instance does not expose WebKit-specific features.
|
4420 |
|
4421 |
|
4422 | - [event: 'disconnected'](#event-disconnected)
|
4423 | - [browser.close()](#browserclose)
|
4424 | - [browser.contexts()](#browsercontexts)
|
4425 | - [browser.isConnected()](#browserisconnected)
|
4426 | - [browser.newContext([options])](#browsernewcontextoptions)
|
4427 | - [browser.newPage([options])](#browsernewpageoptions)
|
4428 | - [browser.version()](#browserversion)
|
4429 |
|
4430 |
|
4431 | ### EvaluationArgument
|
4432 |
|
4433 | Playwright evaluation methods like [page.evaluate(pageFunction[, arg])](#pageevaluatepagefunction-arg) take a single optional argument. This argument can be a mix of [Serializable] values and [JSHandle] or [ElementHandle] instances. Handles are automatically converted to the value they represent.
|
4434 |
|
4435 | See examples for various scenarios:
|
4436 |
|
4437 | ```js
|
4438 | // A primitive value.
|
4439 | await page.evaluate(num => num, 42);
|
4440 |
|
4441 | // An array.
|
4442 | await page.evaluate(array => array.length, [1, 2, 3]);
|
4443 |
|
4444 | // An object.
|
4445 | await page.evaluate(object => object.foo, { foo: 'bar' });
|
4446 |
|
4447 | // A single handle.
|
4448 | const button = await page.$('button');
|
4449 | await page.evaluate(button => button.textContent, button);
|
4450 |
|
4451 | // Alternative notation using elementHandle.evaluate.
|
4452 | await button.evaluate((button, from) => button.textContent.substring(from), 5);
|
4453 |
|
4454 | // Object with multiple handles.
|
4455 | const button1 = await page.$('.button1');
|
4456 | const button2 = await page.$('.button2');
|
4457 | await page.evaluate(
|
4458 | o => o.button1.textContent + o.button2.textContent,
|
4459 | { button1, button2 });
|
4460 |
|
4461 | // Obejct destructuring works. Note that property names must match
|
4462 | // between the destructured object and the argument.
|
4463 | // Also note the required parenthesis.
|
4464 | await page.evaluate(
|
4465 | ({ button1, button2 }) => button1.textContent + button2.textContent,
|
4466 | { button1, button2 });
|
4467 |
|
4468 | // Array works as well. Arbitrary names can be used for destructuring.
|
4469 | // Note the required parenthesis.
|
4470 | await page.evaluate(
|
4471 | ([b1, b2]) => b1.textContent + b2.textContent,
|
4472 | [button1, button2]);
|
4473 |
|
4474 | // Any non-cyclic mix of serializables and handles works.
|
4475 | await page.evaluate(
|
4476 | x => x.button1.textContent + x.list[0].textContent + String(x.foo),
|
4477 | { button1, list: [button2], foo: null });
|
4478 | ```
|
4479 |
|
4480 | ### Environment Variables
|
4481 |
|
4482 | > **NOTE** [playwright-core](https://www.npmjs.com/package/playwright-core) **does not** respect environment variables.
|
4483 |
|
4484 | Playwright looks for certain [environment variables](https://en.wikipedia.org/wiki/Environment_variable) to aid its operations.
|
4485 | If Playwright doesn't find them in the environment, a lowercased variant of these variables will be used from the [npm config](https://docs.npmjs.com/cli/config).
|
4486 |
|
4487 | - `PLAYWRIGHT_DOWNLOAD_HOST` - overwrite URL prefix that is used to download browsers. Note: this includes protocol and might even include path prefix. By default, Playwright uses `https://storage.googleapis.com` to download Chromium and `https://playwright.azureedge.net` to download Webkit & Firefox. You can also use browser-specific download hosts that superceed the `PLAYWRIGHT_DOWNLOAD_HOST` variable:
|
4488 | - `PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST` - host to specify Chromium downloads
|
4489 | - `PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST` - host to specify Firefox downloads
|
4490 | - `PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST` - host to specify Webkit downloads
|
4491 | - `PLAYWRIGHT_BROWSERS_PATH` - specify a shared folder that playwright will use to download browsers and to look for browsers when launching browser instances.
|
4492 | - `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` - set to non-empty value to skip browser downloads altogether.
|
4493 |
|
4494 | ```sh
|
4495 | # Linux/macOS
|
4496 | # Install browsers to the shared location.
|
4497 | $ PLAYWRIGHT_BROWSERS_PATH=$HOME/playwright-browsers npm install --save-dev playwright
|
4498 | # Use shared location to find browsers.
|
4499 | $ PLAYWRIGHT_BROWSERS_PATH=$HOME/playwright-browsers node playwright-script.js
|
4500 |
|
4501 | # Windows
|
4502 | # Install browsers to the shared location.
|
4503 | $ set PLAYWRIGHT_BROWSERS_PATH=%USERPROFILE%\playwright-browsers
|
4504 | $ npm install --save-dev playwright
|
4505 | # Use shared location to find browsers.
|
4506 | $ set PLAYWRIGHT_BROWSERS_PATH=%USERPROFILE%\playwright-browsers
|
4507 | $ node playwright-script.js
|
4508 | ```
|
4509 |
|
4510 |
|
4511 | ### Working with selectors
|
4512 |
|
4513 | Selector describes an element in the page. It can be used to obtain `ElementHandle` (see [page.$()](#pageselector) for example) or shortcut element operations to avoid intermediate handle (see [page.click()](#pageclickselector-options) for example).
|
4514 |
|
4515 | Selector has the following format: `engine=body [>> engine=body]*`. Here `engine` is one of the supported [selector engines](selectors.md) (e.g. `css` or `xpath`), and `body` is a selector body in the format of the particular engine. When multiple `engine=body` clauses are present (separated by `>>`), next one is queried relative to the previous one's result.
|
4516 |
|
4517 | For convenience, selectors in the wrong format are heuristically converted to the right format:
|
4518 | - selector starting with `//` or `..` is assumed to be `xpath=selector`;
|
4519 | - selector starting and ending with a quote (either `"` or `'`) is assumed to be `text=selector`;
|
4520 | - otherwise selector is assumed to be `css=selector`.
|
4521 |
|
4522 | ```js
|
4523 | // queries 'div' css selector
|
4524 | const handle = await page.$('css=div');
|
4525 |
|
4526 | // queries '//html/body/div' xpath selector
|
4527 | const handle = await page.$('xpath=//html/body/div');
|
4528 |
|
4529 | // queries '"foo"' text selector
|
4530 | const handle = await page.$('text="foo"');
|
4531 |
|
4532 | // queries 'span' css selector inside the result of '//html/body/div' xpath selector
|
4533 | const handle = await page.$('xpath=//html/body/div >> css=span');
|
4534 |
|
4535 | // converted to 'css=div'
|
4536 | const handle = await page.$('div');
|
4537 |
|
4538 | // converted to 'xpath=//html/body/div'
|
4539 | const handle = await page.$('//html/body/div');
|
4540 |
|
4541 | // converted to 'text="foo"'
|
4542 | const handle = await page.$('"foo"');
|
4543 |
|
4544 | // queries '../span' xpath selector starting with the result of 'div' css selector
|
4545 | const handle = await page.$('div >> ../span');
|
4546 |
|
4547 | // queries 'span' css selector inside the div handle
|
4548 | const handle = await divHandle.$('css=span');
|
4549 | ```
|
4550 |
|
4551 | ### Working with Chrome Extensions
|
4552 |
|
4553 | Playwright can be used for testing Chrome Extensions.
|
4554 |
|
4555 | > **NOTE** Extensions in Chrome / Chromium currently only work in non-headless mode.
|
4556 |
|
4557 | The following is code for getting a handle to the [background page](https://developer.chrome.com/extensions/background_pages) of an extension whose source is located in `./my-extension`:
|
4558 | ```js
|
4559 | const { chromium } = require('playwright');
|
4560 |
|
4561 | (async () => {
|
4562 | const pathToExtension = require('path').join(__dirname, 'my-extension');
|
4563 | const userDataDir = '/tmp/test-user-data-dir';
|
4564 | const browserContext = await chromium.launchPersistentContext(userDataDir,{
|
4565 | headless: false,
|
4566 | args: [
|
4567 | `--disable-extensions-except=${pathToExtension}`,
|
4568 | `--load-extension=${pathToExtension}`
|
4569 | ]
|
4570 | });
|
4571 | const backgroundPage = browserContext.backgroundPages()[0];
|
4572 | // Test the background page as you would any other page.
|
4573 | await browserContext.close();
|
4574 | })();
|
4575 | ```
|
4576 |
|
4577 | > **NOTE** It is not yet possible to test extension popups or content scripts.
|
4578 |
|
4579 |
|
4580 | [AXNode]: #accessibilitysnapshotoptions "AXNode"
|
4581 | [Accessibility]: #class-accessibility "Accessibility"
|
4582 | [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
|
4583 | [Body]: #class-body "Body"
|
4584 | [BrowserServer]: #class-browserserver "BrowserServer"
|
4585 | [BrowserContext]: #class-browsercontext "BrowserContext"
|
4586 | [BrowserType]: #class-browsertype "BrowserType"
|
4587 | [Browser]: #class-browser "Browser"
|
4588 | [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
|
4589 | [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
|
4590 | [ChromiumBrowser]: #class-chromiumbrowser "ChromiumBrowser"
|
4591 | [ChromiumBrowserContext]: #class-chromiumbrowsercontext "ChromiumBrowserContext"
|
4592 | [ChromiumCoverage]: #class-chromiumcoverage "ChromiumCoverage"
|
4593 | [CDPSession]: #class-cdpsession "CDPSession"
|
4594 | [ConsoleMessage]: #class-consolemessage "ConsoleMessage"
|
4595 | [Dialog]: #class-dialog "Dialog"
|
4596 | [Download]: #class-download "Download"
|
4597 | [ElementHandle]: #class-elementhandle "ElementHandle"
|
4598 | [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
|
4599 | [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
|
4600 | [EvaluationArgument]: #evaluationargument "Evaluation Argument"
|
4601 | [File]: #class-file "https://developer.mozilla.org/en-US/docs/Web/API/File"
|
4602 | [FileChooser]: #class-filechooser "FileChooser"
|
4603 | [FirefoxBrowser]: #class-firefoxbrowser "FirefoxBrowser"
|
4604 | [Frame]: #class-frame "Frame"
|
4605 | [JSHandle]: #class-jshandle "JSHandle"
|
4606 | [Keyboard]: #class-keyboard "Keyboard"
|
4607 | [Logger]: #class-logger "Logger"
|
4608 | [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
|
4609 | [Mouse]: #class-mouse "Mouse"
|
4610 | [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
|
4611 | [Page]: #class-page "Page"
|
4612 | [Playwright]: #class-playwright "Playwright"
|
4613 | [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
|
4614 | [RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
|
4615 | [Request]: #class-request "Request"
|
4616 | [Response]: #class-response "Response"
|
4617 | [Route]: #class-route "Route"
|
4618 | [Selectors]: #class-selectors "Selectors"
|
4619 | [Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
|
4620 | [TimeoutError]: #class-timeouterror "TimeoutError"
|
4621 | [UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
|
4622 | [URL]: https://nodejs.org/api/url.html
|
4623 | [USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
|
4624 | [UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
|
4625 | [WebKitBrowser]: #class-webkitbrowser "WebKitBrowser"
|
4626 | [WebSocket]: #class-websocket "WebSocket"
|
4627 | [Worker]: #class-worker "Worker"
|
4628 | [boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
|
4629 | [function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
|
4630 | [iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
|
4631 | [number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
|
4632 | [origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
|
4633 | [selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
|
4634 | [Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
|
4635 | [string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "String"
|
4636 | [xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"
|