chore: refactor FrameManager and fix docs (#8770)

This commit is contained in:
jrandolf 2022-08-10 23:34:29 +02:00 committed by GitHub
parent 2580347b50
commit d6a88a9768
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
67 changed files with 1312 additions and 1255 deletions

View File

@ -39,7 +39,7 @@ sidebar_label: API
| [TimeoutError](./puppeteer.timeouterror.md) | TimeoutError is emitted whenever certain operations are terminated due to timeout. |
| [Touchscreen](./puppeteer.touchscreen.md) | The Touchscreen class exposes touchscreen events. |
| [Tracing](./puppeteer.tracing.md) | The Tracing class exposes the tracing audit interface. |
| [WebWorker](./puppeteer.webworker.md) | The WebWorker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). |
| [WebWorker](./puppeteer.webworker.md) | This class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). |
## Enumerations

View File

@ -4,7 +4,7 @@ sidebar_label: ElementHandle.$
# ElementHandle.$() method
Runs `element.querySelector` within the page.
Queries the current element for an element matching the given selector.
**Signature:**
@ -18,16 +18,12 @@ class ElementHandle {
## Parameters
| Parameter | Type | Description |
| --------- | -------- | --------------------------- |
| selector | Selector | The selector to query with. |
| Parameter | Type | Description |
| --------- | -------- | -------------------------- |
| selector | Selector | The selector to query for. |
**Returns:**
Promise<[ElementHandle](./puppeteer.elementhandle.md)<[NodeFor](./puppeteer.nodefor.md)<Selector>> \| null>
`null` if no element matches the selector.
## Exceptions
`Error` if the selector has no associated query handler.
A [element handle](./puppeteer.elementhandle.md) to the first element matching the given selector. Otherwise, `null`.

View File

@ -4,7 +4,7 @@ sidebar_label: ElementHandle.$$
# ElementHandle.$$() method
Runs `element.querySelectorAll` within the page.
Queries the current element for all elements matching the given selector.
**Signature:**
@ -18,16 +18,12 @@ class ElementHandle {
## Parameters
| Parameter | Type | Description |
| --------- | -------- | --------------------------- |
| selector | Selector | The selector to query with. |
| Parameter | Type | Description |
| --------- | -------- | -------------------------- |
| selector | Selector | The selector to query for. |
**Returns:**
Promise<Array<[ElementHandle](./puppeteer.elementhandle.md)<[NodeFor](./puppeteer.nodefor.md)<Selector>>>>
`[]` if no element matches the selector.
## Exceptions
`Error` if the selector has no associated query handler.
An array of [element handles](./puppeteer.elementhandle.md) that point to elements matching the given selector.

View File

@ -4,9 +4,9 @@ sidebar_label: ElementHandle.$$eval
# ElementHandle.$$eval() method
This method runs `document.querySelectorAll` within the element and passes it as the first argument to `pageFunction`. If there's no element matching `selector`, the method throws an error.
Runs the given function on an array of elements matching the given selector in the current element.
If `pageFunction` returns a Promise, then `frame.$$eval` would wait for the promise to resolve and return its value.
If the given function returns a promise, then this method will wait till the promise resolves.
**Signature:**
@ -28,17 +28,21 @@ class ElementHandle {
## Parameters
| Parameter | Type | Description |
| ------------ | -------------- | ----------- |
| selector | Selector | |
| pageFunction | Func \| string | |
| args | Params | |
| Parameter | Type | Description |
| ------------ | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | The selector to query for. |
| pageFunction | Func \| string | The function to be evaluated in the element's page's context. An array of elements matching the given selector will be passed to the function as its first argument. |
| args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
## Example 1
A promise to the result of the function.
## Example
HTML:
```html
<div class="feed">
@ -47,9 +51,9 @@ Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
</div>
```
## Example 2
JavaScript:
```ts
```js
const feedHandle = await page.$('.feed');
expect(
await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))

View File

@ -4,9 +4,9 @@ sidebar_label: ElementHandle.$eval
# ElementHandle.$eval() method
This method runs `document.querySelector` within the element and passes it as the first argument to `pageFunction`. If there's no element matching `selector`, the method throws an error.
Runs the given function on the first element matching the given selector in the current element.
If `pageFunction` returns a Promise, then `frame.$eval` would wait for the promise to resolve and return its value.
If the given function returns a promise, then this method will wait till the promise resolves.
**Signature:**
@ -28,16 +28,18 @@ class ElementHandle {
## Parameters
| Parameter | Type | Description |
| ------------ | -------------- | ----------- |
| selector | Selector | |
| pageFunction | Func \| string | |
| args | Params | |
| Parameter | Type | Description |
| ------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | The selector to query for. |
| pageFunction | Func \| string | The function to be evaluated in this element's page's context. The first element matching the selector will be passed in as the first argument. |
| args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
A promise to the result of the function.
## Example
```ts

View File

@ -41,32 +41,32 @@ The constructor for this class is marked as internal. Third-party code should no
## Methods
| Method | Modifiers | Description |
| -------------------------------------------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [$(selector)](./puppeteer.elementhandle._.md) | | Runs <code>element.querySelector</code> within the page. |
| [$$(selector)](./puppeteer.elementhandle.__.md) | | Runs <code>element.querySelectorAll</code> within the page. |
| [$$eval(selector, pageFunction, args)](./puppeteer.elementhandle.__eval.md) | | <p>This method runs <code>document.querySelectorAll</code> within the element and passes it as the first argument to <code>pageFunction</code>. If there's no element matching <code>selector</code>, the method throws an error.</p><p>If <code>pageFunction</code> returns a Promise, then <code>frame.$$eval</code> would wait for the promise to resolve and return its value.</p> |
| [$eval(selector, pageFunction, args)](./puppeteer.elementhandle._eval.md) | | <p>This method runs <code>document.querySelector</code> within the element and passes it as the first argument to <code>pageFunction</code>. If there's no element matching <code>selector</code>, the method throws an error.</p><p>If <code>pageFunction</code> returns a Promise, then <code>frame.$eval</code> would wait for the promise to resolve and return its value.</p> |
| [$x(expression)](./puppeteer.elementhandle._x.md) | | |
| [asElement()](./puppeteer.elementhandle.aselement.md) | | |
| [boundingBox()](./puppeteer.elementhandle.boundingbox.md) | | This method returns the bounding box of the element (relative to the main frame), or <code>null</code> if the element is not visible. |
| [boxModel()](./puppeteer.elementhandle.boxmodel.md) | | This method returns boxes of the element, or <code>null</code> if the element is not visible. |
| [click(this, options)](./puppeteer.elementhandle.click.md) | | This method scrolls element into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to click in the center of the element. If the element is detached from DOM, the method throws an error. |
| [clickablePoint(offset)](./puppeteer.elementhandle.clickablepoint.md) | | Returns the middle point within an element unless a specific offset is provided. |
| [contentFrame()](./puppeteer.elementhandle.contentframe.md) | | Resolves to the content frame for element handles referencing iframe nodes, or null otherwise |
| [drag(this, target)](./puppeteer.elementhandle.drag.md) | | This method creates and captures a dragevent from the element. |
| [dragAndDrop(this, target, options)](./puppeteer.elementhandle.draganddrop.md) | | This method triggers a dragenter, dragover, and drop on the element. |
| [dragEnter(this, data)](./puppeteer.elementhandle.dragenter.md) | | This method creates a <code>dragenter</code> event on the element. |
| [dragOver(this, data)](./puppeteer.elementhandle.dragover.md) | | This method creates a <code>dragover</code> event on the element. |
| [drop(this, data)](./puppeteer.elementhandle.drop.md) | | This method triggers a drop on the element. |
| [focus()](./puppeteer.elementhandle.focus.md) | | Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element. |
| [hover(this)](./puppeteer.elementhandle.hover.md) | | This method scrolls element into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element. If the element is detached from DOM, the method throws an error. |
| [isIntersectingViewport(this, options)](./puppeteer.elementhandle.isintersectingviewport.md) | | Resolves to true if the element is visible in the current viewport. |
| [press(key, options)](./puppeteer.elementhandle.press.md) | | Focuses the element, and then uses [Keyboard.down()](./puppeteer.keyboard.down.md) and [Keyboard.up()](./puppeteer.keyboard.up.md). |
| [screenshot(this, options)](./puppeteer.elementhandle.screenshot.md) | | This method scrolls element into view if needed, and then uses [Page.screenshot()](./puppeteer.page.screenshot.md) to take a screenshot of the element. If the element is detached from DOM, the method throws an error. |
| [select(values)](./puppeteer.elementhandle.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. If there's no <code>&lt;select&gt;</code> element matching <code>selector</code>, the method throws an error. |
| [tap(this)](./puppeteer.elementhandle.tap.md) | | This method scrolls element into view if needed, and then uses [Touchscreen.tap()](./puppeteer.touchscreen.tap.md) to tap in the center of the element. If the element is detached from DOM, the method throws an error. |
| [type(text, options)](./puppeteer.elementhandle.type.md) | | <p>Focuses the element, and then sends a <code>keydown</code>, <code>keypress</code>/<code>input</code>, and <code>keyup</code> event for each character in the text.</p><p>To press a special key, like <code>Control</code> or <code>ArrowDown</code>, use [ElementHandle.press()](./puppeteer.elementhandle.press.md).</p> |
| [uploadFile(this, filePaths)](./puppeteer.elementhandle.uploadfile.md) | | This method expects <code>elementHandle</code> to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). |
| [waitForSelector(selector, options)](./puppeteer.elementhandle.waitforselector.md) | | <p>Wait for the <code>selector</code> to appear within the element. If at the moment of calling the method the <code>selector</code> already exists, the method will return immediately. If the <code>selector</code> doesn't appear after the <code>timeout</code> milliseconds of waiting, the function will throw.</p><p>This method does not work across navigations or if the element is detached from DOM.</p> |
| [waitForXPath(xpath, options)](./puppeteer.elementhandle.waitforxpath.md) | | |
| Method | Modifiers | Description |
| -------------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [$(selector)](./puppeteer.elementhandle._.md) | | Queries the current element for an element matching the given selector. |
| [$$(selector)](./puppeteer.elementhandle.__.md) | | Queries the current element for all elements matching the given selector. |
| [$$eval(selector, pageFunction, args)](./puppeteer.elementhandle.__eval.md) | | <p>Runs the given function on an array of elements matching the given selector in the current element.</p><p>If the given function returns a promise, then this method will wait till the promise resolves.</p> |
| [$eval(selector, pageFunction, args)](./puppeteer.elementhandle._eval.md) | | <p>Runs the given function on the first element matching the given selector in the current element.</p><p>If the given function returns a promise, then this method will wait till the promise resolves.</p> |
| [$x(expression)](./puppeteer.elementhandle._x.md) | | |
| [asElement()](./puppeteer.elementhandle.aselement.md) | | |
| [boundingBox()](./puppeteer.elementhandle.boundingbox.md) | | This method returns the bounding box of the element (relative to the main frame), or <code>null</code> if the element is not visible. |
| [boxModel()](./puppeteer.elementhandle.boxmodel.md) | | This method returns boxes of the element, or <code>null</code> if the element is not visible. |
| [click(this, options)](./puppeteer.elementhandle.click.md) | | This method scrolls element into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to click in the center of the element. If the element is detached from DOM, the method throws an error. |
| [clickablePoint(offset)](./puppeteer.elementhandle.clickablepoint.md) | | Returns the middle point within an element unless a specific offset is provided. |
| [contentFrame()](./puppeteer.elementhandle.contentframe.md) | | Resolves to the content frame for element handles referencing iframe nodes, or null otherwise |
| [drag(this, target)](./puppeteer.elementhandle.drag.md) | | This method creates and captures a dragevent from the element. |
| [dragAndDrop(this, target, options)](./puppeteer.elementhandle.draganddrop.md) | | This method triggers a dragenter, dragover, and drop on the element. |
| [dragEnter(this, data)](./puppeteer.elementhandle.dragenter.md) | | This method creates a <code>dragenter</code> event on the element. |
| [dragOver(this, data)](./puppeteer.elementhandle.dragover.md) | | This method creates a <code>dragover</code> event on the element. |
| [drop(this, data)](./puppeteer.elementhandle.drop.md) | | This method triggers a drop on the element. |
| [focus()](./puppeteer.elementhandle.focus.md) | | Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element. |
| [hover(this)](./puppeteer.elementhandle.hover.md) | | This method scrolls element into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element. If the element is detached from DOM, the method throws an error. |
| [isIntersectingViewport(this, options)](./puppeteer.elementhandle.isintersectingviewport.md) | | Resolves to true if the element is visible in the current viewport. |
| [press(key, options)](./puppeteer.elementhandle.press.md) | | Focuses the element, and then uses [Keyboard.down()](./puppeteer.keyboard.down.md) and [Keyboard.up()](./puppeteer.keyboard.up.md). |
| [screenshot(this, options)](./puppeteer.elementhandle.screenshot.md) | | This method scrolls element into view if needed, and then uses [Page.screenshot()](./puppeteer.page.screenshot.md) to take a screenshot of the element. If the element is detached from DOM, the method throws an error. |
| [select(values)](./puppeteer.elementhandle.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. If there's no <code>&lt;select&gt;</code> element matching <code>selector</code>, the method throws an error. |
| [tap(this)](./puppeteer.elementhandle.tap.md) | | This method scrolls element into view if needed, and then uses [Touchscreen.tap()](./puppeteer.touchscreen.tap.md) to tap in the center of the element. If the element is detached from DOM, the method throws an error. |
| [type(text, options)](./puppeteer.elementhandle.type.md) | | <p>Focuses the element, and then sends a <code>keydown</code>, <code>keypress</code>/<code>input</code>, and <code>keyup</code> event for each character in the text.</p><p>To press a special key, like <code>Control</code> or <code>ArrowDown</code>, use [ElementHandle.press()](./puppeteer.elementhandle.press.md).</p> |
| [uploadFile(this, filePaths)](./puppeteer.elementhandle.uploadfile.md) | | This method expects <code>elementHandle</code> to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). |
| [waitForSelector(selector, options)](./puppeteer.elementhandle.waitforselector.md) | | <p>Wait for an element matching the given selector to appear in the current element.</p><p>Unlike [Frame.waitForSelector()](./puppeteer.frame.waitforselector.md), this method does not work across navigations or if the element is detached from DOM.</p> |
| [waitForXPath(xpath, options)](./puppeteer.elementhandle.waitforxpath.md) | | |

View File

@ -4,9 +4,9 @@ sidebar_label: ElementHandle.waitForSelector
# ElementHandle.waitForSelector() method
Wait for the `selector` to appear within the element. If at the moment of calling the method the `selector` already exists, the method will return immediately. If the `selector` doesn't appear after the `timeout` milliseconds of waiting, the function will throw.
Wait for an element matching the given selector to appear in the current element.
This method does not work across navigations or if the element is detached from DOM.
Unlike [Frame.waitForSelector()](./puppeteer.frame.waitforselector.md), this method does not work across navigations or if the element is detached from DOM.
**Signature:**
@ -21,23 +21,42 @@ class ElementHandle {
## Parameters
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| selector | Selector | A [selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors) of an element to wait for |
| options | Exclude&lt;[WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md), 'root'&gt; | <i>(Optional)</i> Optional waiting parameters |
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| selector | Selector | The selector to query and wait for. |
| options | Exclude&lt;[WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md), 'root'&gt; | <i>(Optional)</i> Options for customizing waiting behavior. |
**Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt; \| null&gt;
Promise which resolves when element specified by selector string is added to DOM. Resolves to `null` if waiting for hidden: `true` and selector is not found in DOM.
An element matching the given selector.
## Remarks
## Exceptions
The optional parameters in `options` are:
Throws if an element matching the given selector doesn't appear.
- `visible`: wait for the selected element to be present in DOM and to be visible, i.e. to not have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.
## Example
- `hidden`: wait for the selected element to not be found in the DOM or to be hidden, i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.
```ts
const puppeteer = require('puppeteer');
- `timeout`: maximum time to wait in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) method.
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
let currentURL;
page
.mainFrame()
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of [
'https://example.com',
'https://google.com',
'https://bbc.com',
]) {
await page.goto(currentURL);
}
await browser.close();
})();
```

View File

@ -14,14 +14,14 @@ export declare class FileChooser
## Remarks
`FileChooser` objects are returned via the `page.waitForFileChooser` method.
`FileChooser` instances are returned via the [Page.waitForFileChooser()](./puppeteer.page.waitforfilechooser.md) method.
In browsers, only one file chooser can be opened at a time. All file choosers must be accepted or canceled. Not doing so will prevent subsequent file choosers from appearing.
The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `FileChooser` class.
## Example
An example of using `FileChooser`:
```ts
const [fileChooser] = await Promise.all([
page.waitForFileChooser(),
@ -30,8 +30,6 @@ const [fileChooser] = await Promise.all([
await fileChooser.accept(['/tmp/myfile.pdf']);
```
\*\*NOTE\*\* In browsers, only one file chooser can be opened at a time. All file choosers must be accepted or canceled. Not doing so will prevent subsequent file choosers from appearing.
## Methods
| Method | Modifiers | Description |

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.$
# Frame.$() method
This method queries the frame for the given selector.
Queries the frame for an element matching the given selector.
**Signature:**
@ -18,12 +18,12 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | -------- | ------------------------ |
| selector | Selector | a selector to query for. |
| Parameter | Type | Description |
| --------- | -------- | -------------------------- |
| selector | Selector | The selector to query for. |
**Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt; \| null&gt;
A promise which resolves to an `ElementHandle` pointing at the element, or `null` if it was not found.
A [element handle](./puppeteer.elementhandle.md) to the first element matching the given selector. Otherwise, `null`.

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.$$
# Frame.$$() method
This runs `document.querySelectorAll` in the frame and returns the result.
Queries the frame for all elements matching the given selector.
**Signature:**
@ -18,12 +18,12 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | -------- | ------------------------ |
| selector | Selector | a selector to search for |
| Parameter | Type | Description |
| --------- | -------- | -------------------------- |
| selector | Selector | The selector to query for. |
**Returns:**
Promise&lt;Array&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt;&gt;&gt;
An array of element handles pointing to the found frame elements.
An array of [element handles](./puppeteer.elementhandle.md) that point to elements matching the given selector.

View File

@ -4,6 +4,10 @@ sidebar_label: Frame.$$eval
# Frame.$$eval() method
Runs the given function on an array of elements matching the given selector in the frame.
If the given function returns a promise, then this method will wait till the promise resolves.
**Signature:**
```typescript
@ -24,24 +28,20 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| ------------ | -------------- | --------------------------------------------------------- |
| selector | Selector | the selector to query for |
| pageFunction | Func \| string | the function to be evaluated in the frame's context |
| args | Params | additional arguments to pass to <code>pageFunction</code> |
| Parameter | Type | Description |
| ------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | The selector to query for. |
| pageFunction | Func \| string | The function to be evaluated in the frame's context. An array of elements matching the given selector will be passed to the function as its first argument. |
| args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
## Remarks
This method runs `Array.from(document.querySelectorAll(selector))` within the frame and passes it as the first argument to `pageFunction`.
If `pageFunction` returns a Promise, then `frame.$$eval` would wait for the promise to resolve and return its value.
A promise to the result of the function.
## Example
```ts
```js
const divsCounts = await frame.$$eval('div', divs => divs.length);
```

View File

@ -4,6 +4,10 @@ sidebar_label: Frame.$eval
# Frame.$eval() method
Runs the given function on the first element matching the given selector in the frame.
If the given function returns a promise, then this method will wait till the promise resolves.
**Signature:**
```typescript
@ -24,21 +28,17 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| ------------ | -------------- | --------------------------------------------------------- |
| selector | Selector | the selector to query for |
| pageFunction | Func \| string | the function to be evaluated in the frame's context |
| args | Params | additional arguments to pass to <code>pageFunction</code> |
| Parameter | Type | Description |
| ------------ | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | The selector to query for. |
| pageFunction | Func \| string | The function to be evaluated in the frame's context. The first element matching the selector will be passed to the function as its first argument. |
| args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
## Remarks
This method runs `document.querySelector` within the frame and passes it as the first argument to `pageFunction`.
If `pageFunction` returns a Promise, then `frame.$eval` would wait for the promise to resolve and return its value.
A promise to the result of the function.
## Example

View File

@ -4,7 +4,11 @@ sidebar_label: Frame.$x
# Frame.$x() method
This method evaluates the given XPath expression and returns the results.
> Warning: This API is now obsolete.
>
> Use [Frame.$$()](./puppeteer.frame.__.md) with the `xpath` prefix.
>
> This method evaluates the given XPath expression and returns the results.
**Signature:**

View File

@ -18,9 +18,9 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | ------------------------------------------------------------------- | ---------------------------------------- |
| options | [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) | configure the script to add to the page. |
| Parameter | Type | Description |
| --------- | ------------------------------------------------------------------- | ----------------------- |
| options | [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) | Options for the script. |
**Returns:**

View File

@ -10,18 +10,20 @@ Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<s
```typescript
class Frame {
addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle<Node>>;
addStyleTag(
options: FrameAddStyleTagOptions
): Promise<ElementHandle<HTMLStyleElement | HTMLLinkElement>>;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ----------------------------------------------------------------- | ------------------------------------- |
| options | [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) | configure the CSS to add to the page. |
| Parameter | Type | Description |
| --------- | ----------------------------------------------------------------- | --------------------------- |
| options | [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) | Options for the style link. |
**Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;Node&gt;&gt;
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;HTMLStyleElement \| HTMLLinkElement&gt;&gt;
a promise that resolves to the added tag when the stylesheets's `onload` event fires or when the CSS content was injected into the frame.

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.click
# Frame.click() method
This method clicks the first element found that matches `selector`.
Clicks the first element found that matches `selector`.
**Signature:**
@ -23,10 +23,10 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| selector | string | the selector to search for to click. If there are multiple elements, the first will be clicked. |
| options | { delay?: number; button?: [MouseButton](./puppeteer.mousebutton.md); clickCount?: number; } | <i>(Optional)</i> |
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------------- | -------------------------- |
| selector | string | The selector to query for. |
| options | { delay?: number; button?: [MouseButton](./puppeteer.mousebutton.md); clickCount?: number; } | <i>(Optional)</i> |
**Returns:**
@ -34,11 +34,9 @@ Promise&lt;void&gt;
## Remarks
This method scrolls the element into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to click in the center of the element. If there's no element matching `selector`, the method throws an error.
If `click()` triggers a navigation event and there's a separate `page.waitForNavigation()` promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:
Bear in mind that if `click()` triggers a navigation event and there's a separate `page.waitForNavigation()` promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:
```javascript
```ts
const [response] = await Promise.all([
page.waitForNavigation(waitOptions),
frame.click(selector, clickOptions),

View File

@ -16,4 +16,4 @@ class Frame {
Promise&lt;string&gt;
the full HTML contents of the frame, including the doctype.
The full HTML contents of the frame, including the DOCTYPE.

View File

@ -4,6 +4,8 @@ sidebar_label: Frame.evaluate
# Frame.evaluate() method
Behaves identically to [Page.evaluate()](./puppeteer.page.evaluate.md) except it's run within the the context of this frame.
**Signature:**
```typescript
@ -28,7 +30,3 @@ class Frame {
**Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
## Remarks
This method behaves identically to [Page.evaluate()](./puppeteer.page.evaluate.md) except it's run within the context of the `frame`, rather than the entire page.

View File

@ -4,6 +4,8 @@ sidebar_label: Frame.evaluateHandle
# Frame.evaluateHandle() method
Behaves identically to [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md) except it's run within the context of this frame.
**Signature:**
```typescript
@ -28,9 +30,3 @@ class Frame {
**Returns:**
Promise&lt;[HandleFor](./puppeteer.handlefor.md)&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;&gt;
## Remarks
The only difference between [Frame.evaluate()](./puppeteer.frame.evaluate.md) and `frame.evaluateHandle` is that `evaluateHandle` will return the value wrapped in an in-page object.
This method behaves identically to [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md) except it's run within the context of the `frame`, rather than the entire page.

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.focus
# Frame.focus() method
This method fetches an element with `selector` and focuses it.
Focuses the first element that matches the `selector`.
**Signature:**
@ -16,14 +16,14 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | ------ | ------------------------------------------------------------------------------------------------- |
| selector | string | the selector for the element to focus. If there are multiple elements, the first will be focused. |
| Parameter | Type | Description |
| --------- | ------ | -------------------------- |
| selector | string | The selector to query for. |
**Returns:**
Promise&lt;void&gt;
## Remarks
## Exceptions
If there's no element matching `selector`, the method throws an error.
Throws if there's no element matching `selector`.

View File

@ -4,6 +4,8 @@ sidebar_label: Frame.goto
# Frame.goto() method
Navigates a frame to the given url.
**Signature:**
```typescript
@ -32,20 +34,20 @@ Promise&lt;[HTTPResponse](./puppeteer.httpresponse.md) \| null&gt;
A promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
## Exceptions
This method will throw an error if:
- there's an SSL error (e.g. in case of self-signed certificates). - target URL is invalid. - the `timeout` is exceeded during navigation. - the remote server does not respond or is unreachable. - the main resource failed to load.
This method 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 [HTTPResponse.status()](./puppeteer.httpresponse.status.md).
## Remarks
`frame.goto` will throw an error if: - there's an SSL error (e.g. in case of self-signed certificates).
Navigation to `about:blank` or navigation to the same URL with a different hash will succeed and return `null`.
- target URL is invalid.
:::warning
- the `timeout` is exceeded during navigation.
Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
- the remote server does not respond or is unreachable.
- the main resource failed to load.
`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 [HTTPResponse.status()](./puppeteer.httpresponse.status.md).
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`.
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).
:::

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.hover
# Frame.hover() method
This method fetches an element with `selector`, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element.
Hovers the pointer over the center of the first element that matches the `selector`.
**Signature:**
@ -16,14 +16,14 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | ------ | ------------------------------------------------------------------------------------------------- |
| selector | string | the selector for the element to hover. If there are multiple elements, the first will be hovered. |
| Parameter | Type | Description |
| --------- | ------ | -------------------------- |
| selector | string | The selector to query for. |
**Returns:**
Promise&lt;void&gt;
## Remarks
## Exceptions
If there's no element matching `selector`, the method throws an
Throws if there's no element matching `selector`.

View File

@ -17,5 +17,3 @@ class Frame {
boolean
`true` if the frame is an OOP frame, or `false` otherwise.
## Remarks

View File

@ -16,11 +16,7 @@ export declare class Frame
`Frame` object lifecycles are controlled by three events that are all dispatched on the page object:
- [PageEmittedEvents.FrameAttached](./puppeteer.pageemittedevents.md)
- [PageEmittedEvents.FrameNavigated](./puppeteer.pageemittedevents.md)
- [PageEmittedEvents.FrameDetached](./puppeteer.pageemittedevents.md)
- [PageEmittedEvents.FrameAttached](./puppeteer.pageemittedevents.md) - [PageEmittedEvents.FrameNavigated](./puppeteer.pageemittedevents.md) - [PageEmittedEvents.FrameDetached](./puppeteer.pageemittedevents.md)
The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `Frame` class.
@ -59,37 +55,37 @@ console.log(text);
## Methods
| Method | Modifiers | Description |
| ------------------------------------------------------------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [$(selector)](./puppeteer.frame._.md) | | This method queries the frame for the given selector. |
| [$$(selector)](./puppeteer.frame.__.md) | | This runs <code>document.querySelectorAll</code> in the frame and returns the result. |
| [$$eval(selector, pageFunction, args)](./puppeteer.frame.__eval.md) | | |
| [$eval(selector, pageFunction, args)](./puppeteer.frame._eval.md) | | |
| [$x(expression)](./puppeteer.frame._x.md) | | This method evaluates the given XPath expression and returns the results. |
| [addScriptTag(options)](./puppeteer.frame.addscripttag.md) | | Adds a <code>&lt;script&gt;</code> tag into the page with the desired url or content. |
| [addStyleTag(options)](./puppeteer.frame.addstyletag.md) | | Adds a <code>&lt;link rel=&quot;stylesheet&quot;&gt;</code> tag into the page with the desired url or a <code>&lt;style type=&quot;text/css&quot;&gt;</code> tag with the content. |
| [childFrames()](./puppeteer.frame.childframes.md) | | |
| [click(selector, options)](./puppeteer.frame.click.md) | | This method clicks the first element found that matches <code>selector</code>. |
| [content()](./puppeteer.frame.content.md) | | |
| [evaluate(pageFunction, args)](./puppeteer.frame.evaluate.md) | | |
| [evaluateHandle(pageFunction, args)](./puppeteer.frame.evaluatehandle.md) | | |
| [executionContext()](./puppeteer.frame.executioncontext.md) | | |
| [focus(selector)](./puppeteer.frame.focus.md) | | This method fetches an element with <code>selector</code> and focuses it. |
| [goto(url, options)](./puppeteer.frame.goto.md) | | |
| [hover(selector)](./puppeteer.frame.hover.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element. |
| [isDetached()](./puppeteer.frame.isdetached.md) | | |
| [isOOPFrame()](./puppeteer.frame.isoopframe.md) | | |
| [name()](./puppeteer.frame.name.md) | | |
| [page()](./puppeteer.frame.page.md) | | |
| [parentFrame()](./puppeteer.frame.parentframe.md) | | |
| [select(selector, values)](./puppeteer.frame.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. |
| [setContent(html, options)](./puppeteer.frame.setcontent.md) | | Set the content of the frame. |
| [tap(selector)](./puppeteer.frame.tap.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.touchscreen](./puppeteer.page.touchscreen.md) to tap in the center of the element. |
| [title()](./puppeteer.frame.title.md) | | |
| [type(selector, text, options)](./puppeteer.frame.type.md) | | Sends a <code>keydown</code>, <code>keypress</code>/<code>input</code>, and <code>keyup</code> event for each character in the text. |
| [url()](./puppeteer.frame.url.md) | | |
| [waitForFunction(pageFunction, options, args)](./puppeteer.frame.waitforfunction.md) | | |
| [waitForNavigation(options)](./puppeteer.frame.waitfornavigation.md) | | |
| [waitForSelector(selector, options)](./puppeteer.frame.waitforselector.md) | | |
| [waitForTimeout(milliseconds)](./puppeteer.frame.waitfortimeout.md) | | Causes your script to wait for the given number of milliseconds. |
| [waitForXPath(xpath, options)](./puppeteer.frame.waitforxpath.md) | | |
| Method | Modifiers | Description |
| ------------------------------------------------------------------------------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [$(selector)](./puppeteer.frame._.md) | | Queries the frame for an element matching the given selector. |
| [$$(selector)](./puppeteer.frame.__.md) | | Queries the frame for all elements matching the given selector. |
| [$$eval(selector, pageFunction, args)](./puppeteer.frame.__eval.md) | | <p>Runs the given function on an array of elements matching the given selector in the frame.</p><p>If the given function returns a promise, then this method will wait till the promise resolves.</p> |
| [$eval(selector, pageFunction, args)](./puppeteer.frame._eval.md) | | <p>Runs the given function on the first element matching the given selector in the frame.</p><p>If the given function returns a promise, then this method will wait till the promise resolves.</p> |
| [$x(expression)](./puppeteer.frame._x.md) | | |
| [addScriptTag(options)](./puppeteer.frame.addscripttag.md) | | Adds a <code>&lt;script&gt;</code> tag into the page with the desired url or content. |
| [addStyleTag(options)](./puppeteer.frame.addstyletag.md) | | Adds a <code>&lt;link rel=&quot;stylesheet&quot;&gt;</code> tag into the page with the desired url or a <code>&lt;style type=&quot;text/css&quot;&gt;</code> tag with the content. |
| [childFrames()](./puppeteer.frame.childframes.md) | | |
| [click(selector, options)](./puppeteer.frame.click.md) | | Clicks the first element found that matches <code>selector</code>. |
| [content()](./puppeteer.frame.content.md) | | |
| [evaluate(pageFunction, args)](./puppeteer.frame.evaluate.md) | | Behaves identically to [Page.evaluate()](./puppeteer.page.evaluate.md) except it's run within the the context of this frame. |
| [evaluateHandle(pageFunction, args)](./puppeteer.frame.evaluatehandle.md) | | Behaves identically to [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md) except it's run within the context of this frame. |
| [executionContext()](./puppeteer.frame.executioncontext.md) | | |
| [focus(selector)](./puppeteer.frame.focus.md) | | Focuses the first element that matches the <code>selector</code>. |
| [goto(url, options)](./puppeteer.frame.goto.md) | | Navigates a frame to the given url. |
| [hover(selector)](./puppeteer.frame.hover.md) | | Hovers the pointer over the center of the first element that matches the <code>selector</code>. |
| [isDetached()](./puppeteer.frame.isdetached.md) | | |
| [isOOPFrame()](./puppeteer.frame.isoopframe.md) | | |
| [name()](./puppeteer.frame.name.md) | | |
| [page()](./puppeteer.frame.page.md) | | |
| [parentFrame()](./puppeteer.frame.parentframe.md) | | |
| [select(selector, values)](./puppeteer.frame.select.md) | | Selects a set of value on the first <code>&lt;select&gt;</code> element that matches the <code>selector</code>. |
| [setContent(html, options)](./puppeteer.frame.setcontent.md) | | Set the content of the frame. |
| [tap(selector)](./puppeteer.frame.tap.md) | | Taps the first element that matches the <code>selector</code>. |
| [title()](./puppeteer.frame.title.md) | | |
| [type(selector, text, options)](./puppeteer.frame.type.md) | | Sends a <code>keydown</code>, <code>keypress</code>/<code>input</code>, and <code>keyup</code> event for each character in the text. |
| [url()](./puppeteer.frame.url.md) | | |
| [waitForFunction(pageFunction, options, args)](./puppeteer.frame.waitforfunction.md) | | |
| [waitForNavigation(options)](./puppeteer.frame.waitfornavigation.md) | | <p>Waits for the frame to navigate. It is useful for when you run code which will indirectly cause the frame to navigate.</p><p>Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.</p> |
| [waitForSelector(selector, options)](./puppeteer.frame.waitforselector.md) | | <p>Wait for an element matching the given selector to appear in the frame.</p><p>This method works across navigations.</p> |
| [waitForTimeout(milliseconds)](./puppeteer.frame.waitfortimeout.md) | | Causes your script to wait for the given number of milliseconds. |
| [waitForXPath(xpath, options)](./puppeteer.frame.waitforxpath.md) | | |

View File

@ -16,10 +16,8 @@ class Frame {
string
the frame's `name` attribute as specified in the tag.
The frame's `name` attribute as specified in the tag.
## Remarks
If the name is empty, it returns the `id` attribute instead.
Note: This value is calculated once when the frame is created, and will not update if the attribute is changed later.
This value is calculated once when the frame is created, and will not update if the attribute is changed later.

View File

@ -16,4 +16,4 @@ class Frame {
[Page](./puppeteer.page.md)
a page associated with the frame.
The page associated with the frame.

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.select
# Frame.select() method
Triggers a `change` and `input` event once all the provided options have been selected.
Selects a set of value on the first `<select>` element that matches the `selector`.
**Signature:**
@ -16,10 +16,10 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | string | a selector to query the frame for |
| values | string\[\] | an array of values to select. If the <code>&lt;select&gt;</code> has the <code>multiple</code> attribute, all values are considered, otherwise only the first one is taken into account. |
| Parameter | Type | Description |
| --------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | string | The selector to query for. |
| values | string\[\] | The array of values to select. If the <code>&lt;select&gt;</code> has the <code>multiple</code> attribute, all values are considered, otherwise only the first one is taken into account. |
**Returns:**
@ -27,9 +27,9 @@ Promise&lt;string\[\]&gt;
the list of values that were successfully selected.
## Remarks
## Exceptions
If there's no `<select>` element matching `selector`, the method throws an error.
Throws if there's no `<select>` matching `selector`.
## Example

View File

@ -25,7 +25,7 @@ class Frame {
| Parameter | Type | Description |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| html | string | HTML markup to assign to the page. |
| options | { timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)\[\]; } | <i>(Optional)</i> options to configure how long before timing out and at what point to consider the content setting successful. |
| options | { timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)\[\]; } | <i>(Optional)</i> Options to configure how long before timing out and at what point to consider the content setting successful. |
**Returns:**

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.tap
# Frame.tap() method
This method fetches an element with `selector`, scrolls it into view if needed, and then uses [Page.touchscreen](./puppeteer.page.touchscreen.md) to tap in the center of the element.
Taps the first element that matches the `selector`.
**Signature:**
@ -16,16 +16,14 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | ------ | -------------------- |
| selector | string | the selector to tap. |
| Parameter | Type | Description |
| --------- | ------ | -------------------------- |
| selector | string | The selector to query for. |
**Returns:**
Promise&lt;void&gt;
a promise that resolves when the element has been tapped.
## Exceptions
## Remarks
If there's no element matching `selector`, the method throws an error.
Throws if there's no element matching `selector`.

View File

@ -32,8 +32,6 @@ class Frame {
Promise&lt;void&gt;
a promise that resolves when the typing is complete.
## Remarks
To press a special key, like `Control` or `ArrowDown`, use [Keyboard.press()](./puppeteer.keyboard.press.md).

View File

@ -33,8 +33,6 @@ Promise&lt;[HandleFor](./puppeteer.handlefor.md)&lt;Awaited&lt;ReturnType&lt;Fun
the promise which resolve when the `pageFunction` returns a truthy value.
## Remarks
## Example
The `waitForFunction` can be used to observe viewport size change:

View File

@ -4,6 +4,10 @@ sidebar_label: Frame.waitForNavigation
# Frame.waitForNavigation() method
Waits for the frame to navigate. It is useful for when you run code which will indirectly cause the frame to navigate.
Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
**Signature:**
```typescript
@ -27,9 +31,7 @@ Promise&lt;[HTTPResponse](./puppeteer.httpresponse.md) \| null&gt;
a promise that resolves when the frame navigates to a new URL.
## Remarks
This resolves when the frame navigates to a new URL. It is useful for when you run code which will indirectly cause the frame to navigate. Consider this example:
## Example
```ts
const [response] = await Promise.all([
@ -39,5 +41,3 @@ const [response] = await Promise.all([
frame.click('a.my-link'),
]);
```
Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.

View File

@ -4,6 +4,10 @@ sidebar_label: Frame.waitForSelector
# Frame.waitForSelector() method
Wait for an element matching the given selector to appear in the frame.
This method works across navigations.
**Signature:**
```typescript
@ -17,22 +21,20 @@ class Frame {
## Parameters
| Parameter | Type | Description |
| --------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| selector | Selector | the selector to wait for. |
| options | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | <i>(Optional)</i> options to define if the element should be visible and how long to wait before timing out. |
| Parameter | Type | Description |
| --------- | --------------------------------------------------------------- | ----------------------------------------------------------- |
| selector | Selector | The selector to query and wait for. |
| options | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | <i>(Optional)</i> Options for customizing waiting behavior. |
**Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt; \| null&gt;
a promise which resolves when an element matching the selector string is added to the DOM.
An element matching the given selector.
## Remarks
## Exceptions
Wait for the `selector` to appear in page. If at the moment of calling the method the `selector` already exists, the method will return immediately. If the selector doesn't appear after the `timeout` milliseconds of waiting, the function will throw.
This method works across navigations.
Throws if an element matching the given selector doesn't appear.
## Example

View File

@ -4,6 +4,10 @@ sidebar_label: Frame.waitForTimeout
# Frame.waitForTimeout() method
> Warning: This API is now obsolete.
>
> DO NOT USE.
Causes your script to wait for the given number of milliseconds.
**Signature:**

View File

@ -4,7 +4,7 @@ sidebar_label: GeolocationOptions.latitude
# GeolocationOptions.latitude property
Longitude between -180 and 180.
Longitude between `-180` and `180`.
**Signature:**

View File

@ -4,7 +4,7 @@ sidebar_label: GeolocationOptions.longitude
# GeolocationOptions.longitude property
Latitude between -90 and 90.
Latitude between `-90` and `90`.
**Signature:**

View File

@ -12,8 +12,8 @@ export interface GeolocationOptions
## Properties
| Property | Modifiers | Type | Description |
| -------------------------------------------------------- | --------- | ------ | ------------------------------------------------------- |
| [accuracy?](./puppeteer.geolocationoptions.accuracy.md) | | number | <i>(Optional)</i> Optional non-negative accuracy value. |
| [latitude](./puppeteer.geolocationoptions.latitude.md) | | number | Longitude between -180 and 180. |
| [longitude](./puppeteer.geolocationoptions.longitude.md) | | number | Latitude between -90 and 90. |
| Property | Modifiers | Type | Description |
| -------------------------------------------------------- | --------- | ------ | --------------------------------------------------------- |
| [accuracy?](./puppeteer.geolocationoptions.accuracy.md) | | number | <i>(Optional)</i> Optional non-negative accuracy value. |
| [latitude](./puppeteer.geolocationoptions.latitude.md) | | number | Longitude between <code>-180</code> and <code>180</code>. |
| [longitude](./puppeteer.geolocationoptions.longitude.md) | | number | Latitude between <code>-90</code> and <code>90</code>. |

View File

@ -4,6 +4,10 @@ sidebar_label: Page.evaluate
# Page.evaluate() method
Evaluates a function in the page's context and returns the result.
If the function passed to `page.evaluteHandle` returns a Promise, the function will wait for the promise to resolve and return its value.
**Signature:**
```typescript
@ -31,12 +35,6 @@ Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
the return value of `pageFunction`.
## Remarks
Evaluates a function in the page's context and returns the result.
If the function passed to `page.evaluteHandle` returns a Promise, the function will wait for the promise to resolve and return its value.
## Example 1
```ts

View File

@ -8,7 +8,11 @@ The method adds a function called `name` on the page's `window` object. When cal
If the puppeteerFunction returns a `Promise`, it will be awaited.
NOTE: Functions installed via `page.exposeFunction` survive navigations.
:::note
Functions installed via `page.exposeFunction` survive navigations.
:::note
**Signature:**
@ -36,7 +40,7 @@ class Page {
Promise&lt;void&gt;
## Example
## Example 1
An example of adding an `md5` function into the page:
@ -61,6 +65,8 @@ const crypto = require('crypto');
})();
```
## Example 2
An example of adding a `window.readfile` function into the page:
```ts

View File

@ -74,84 +74,84 @@ page.off('request', logRequest);
## Methods
| Method | Modifiers | Description |
| ------------------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [$(selector)](./puppeteer.page._.md) | | Runs <code>document.querySelector</code> within the page. If no element matches the selector, the return value resolves to <code>null</code>. |
| [$$(selector)](./puppeteer.page.__.md) | | The method runs <code>document.querySelectorAll</code> within the page. If no elements match the selector, the return value resolves to <code>[]</code>. |
| [$$eval(selector, pageFunction, args)](./puppeteer.page.__eval.md) | | This method runs <code>Array.from(document.querySelectorAll(selector))</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$eval(selector, pageFunction, args)](./puppeteer.page._eval.md) | | This method runs <code>document.querySelector</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$x(expression)](./puppeteer.page._x.md) | | The method evaluates the XPath expression relative to the page document as its context node. If there are no such elements, the method resolves to an empty array. |
| [addScriptTag(options)](./puppeteer.page.addscripttag.md) | | Adds a <code>&lt;script&gt;</code> tag into the page with the desired URL or content. |
| [addStyleTag(options)](./puppeteer.page.addstyletag.md) | | Adds a <code>&lt;link rel=&quot;stylesheet&quot;&gt;</code> tag into the page with the desired URL or a <code>&lt;style type=&quot;text/css&quot;&gt;</code> tag with the content. |
| [authenticate(credentials)](./puppeteer.page.authenticate.md) | | Provide credentials for <code>HTTP authentication</code>. |
| [bringToFront()](./puppeteer.page.bringtofront.md) | | Brings page to front (activates tab). |
| [browser()](./puppeteer.page.browser.md) | | Get the browser the page belongs to. |
| [browserContext()](./puppeteer.page.browsercontext.md) | | Get the browser context that the page belongs to. |
| [click(selector, options)](./puppeteer.page.click.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to click in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [close(options)](./puppeteer.page.close.md) | | |
| [content()](./puppeteer.page.content.md) | | |
| [cookies(urls)](./puppeteer.page.cookies.md) | | If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned. |
| [createPDFStream(options)](./puppeteer.page.createpdfstream.md) | | Generates a PDF of the page with the <code>print</code> CSS media type. |
| [deleteCookie(cookies)](./puppeteer.page.deletecookie.md) | | |
| [emulate(options)](./puppeteer.page.emulate.md) | | Emulates given device metrics and user agent. |
| [emulateCPUThrottling(factor)](./puppeteer.page.emulatecputhrottling.md) | | Enables CPU throttling to emulate slow CPUs. |
| [emulateIdleState(overrides)](./puppeteer.page.emulateidlestate.md) | | Emulates the idle state. If no arguments set, clears idle state emulation. |
| [emulateMediaFeatures(features)](./puppeteer.page.emulatemediafeatures.md) | | |
| [emulateMediaType(type)](./puppeteer.page.emulatemediatype.md) | | |
| [emulateNetworkConditions(networkConditions)](./puppeteer.page.emulatenetworkconditions.md) | | |
| [emulateTimezone(timezoneId)](./puppeteer.page.emulatetimezone.md) | | |
| [emulateVisionDeficiency(type)](./puppeteer.page.emulatevisiondeficiency.md) | | Simulates the given vision deficiency on the page. |
| [evaluate(pageFunction, args)](./puppeteer.page.evaluate.md) | | |
| [evaluateHandle(pageFunction, args)](./puppeteer.page.evaluatehandle.md) | | |
| [evaluateOnNewDocument(pageFunction, args)](./puppeteer.page.evaluateonnewdocument.md) | | <p>Adds a function which would be invoked in one of the following scenarios:</p><p>- whenever the page is navigated</p><p>- whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame.</p><p>The function is invoked 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 <code>Math.random</code>.</p> |
| [exposeFunction(name, pptrFunction)](./puppeteer.page.exposefunction.md) | | <p>The method adds a function called <code>name</code> on the page's <code>window</code> object. When called, the function executes <code>puppeteerFunction</code> in node.js and returns a <code>Promise</code> which resolves to the return value of <code>puppeteerFunction</code>.</p><p>If the puppeteerFunction returns a <code>Promise</code>, it will be awaited.</p><p>NOTE: Functions installed via <code>page.exposeFunction</code> survive navigations.</p> |
| [focus(selector)](./puppeteer.page.focus.md) | | This method fetches an element with <code>selector</code> and focuses it. If there's no element matching <code>selector</code>, the method throws an error. |
| [frames()](./puppeteer.page.frames.md) | | |
| [goBack(options)](./puppeteer.page.goback.md) | | This method navigate to the previous page in history. |
| [goForward(options)](./puppeteer.page.goforward.md) | | This method navigate to the next page in history. |
| [goto(url, options)](./puppeteer.page.goto.md) | | |
| [hover(selector)](./puppeteer.page.hover.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [isClosed()](./puppeteer.page.isclosed.md) | | Indicates that the page has been closed. |
| [isDragInterceptionEnabled()](./puppeteer.page.isdraginterceptionenabled.md) | | |
| [isJavaScriptEnabled()](./puppeteer.page.isjavascriptenabled.md) | | |
| [mainFrame()](./puppeteer.page.mainframe.md) | | |
| [metrics()](./puppeteer.page.metrics.md) | | |
| [off(eventName, handler)](./puppeteer.page.off.md) | | |
| [on(eventName, handler)](./puppeteer.page.on.md) | | <p>Listen to page events.</p><p>:::note</p><p>This method exists to define event typings and handle proper wireup of cooperative request interception. Actual event listening and dispatching is delegated to [EventEmitter](./puppeteer.eventemitter.md).</p><p>:::</p> |
| [once(eventName, handler)](./puppeteer.page.once.md) | | |
| [pdf(options)](./puppeteer.page.pdf.md) | | |
| [queryObjects(prototypeHandle)](./puppeteer.page.queryobjects.md) | | This method iterates the JavaScript heap and finds all objects with the given prototype. |
| [reload(options)](./puppeteer.page.reload.md) | | |
| [screenshot(options)](./puppeteer.page.screenshot.md) | | |
| [select(selector, values)](./puppeteer.page.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. If there's no <code>&lt;select&gt;</code> element matching <code>selector</code>, the method throws an error. |
| [setBypassCSP(enabled)](./puppeteer.page.setbypasscsp.md) | | Toggles bypassing page's Content-Security-Policy. |
| [setCacheEnabled(enabled)](./puppeteer.page.setcacheenabled.md) | | Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled. |
| [setContent(html, options)](./puppeteer.page.setcontent.md) | | |
| [setCookie(cookies)](./puppeteer.page.setcookie.md) | | |
| [setDefaultNavigationTimeout(timeout)](./puppeteer.page.setdefaultnavigationtimeout.md) | | <p>This setting will change the default maximum navigation time for the following methods and related shortcuts:</p><p>- [page.goBack(options)](./puppeteer.page.goback.md)</p><p>- [page.goForward(options)](./puppeteer.page.goforward.md)</p><p>- [page.goto(url,options)](./puppeteer.page.goto.md)</p><p>- [page.reload(options)](./puppeteer.page.reload.md)</p><p>- [page.setContent(html,options)](./puppeteer.page.setcontent.md)</p><p>- [page.waitForNavigation(options)](./puppeteer.page.waitfornavigation.md)</p> |
| [setDefaultTimeout(timeout)](./puppeteer.page.setdefaulttimeout.md) | | |
| [setDragInterception(enabled)](./puppeteer.page.setdraginterception.md) | | |
| [setExtraHTTPHeaders(headers)](./puppeteer.page.setextrahttpheaders.md) | | The extra HTTP headers will be sent with every request the page initiates. NOTE: All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldnt impact your server code.) NOTE: page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests. |
| [setGeolocation(options)](./puppeteer.page.setgeolocation.md) | | Sets the page's geolocation. |
| [setJavaScriptEnabled(enabled)](./puppeteer.page.setjavascriptenabled.md) | | |
| [setOfflineMode(enabled)](./puppeteer.page.setofflinemode.md) | | |
| [setRequestInterception(value)](./puppeteer.page.setrequestinterception.md) | | <p>Activating request interception enables [HTTPRequest.abort()](./puppeteer.httprequest.abort.md), [HTTPRequest.continue()](./puppeteer.httprequest.continue.md) and [HTTPRequest.respond()](./puppeteer.httprequest.respond.md) methods. This provides the capability to modify network requests that are made by a page.</p><p>Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.</p><p>NOTE: Enabling request interception disables page caching.</p><p>See the [Request interception guide](https://pptr.dev/next/guides/request-interception) for more details.</p> |
| [setUserAgent(userAgent, userAgentMetadata)](./puppeteer.page.setuseragent.md) | | |
| [setViewport(viewport)](./puppeteer.page.setviewport.md) | | <p><code>page.setViewport</code> will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.</p><p>In the case of multiple pages in a single browser, each page can have its own viewport size.</p> |
| [tap(selector)](./puppeteer.page.tap.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.touchscreen](./puppeteer.page.touchscreen.md) to tap in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [target()](./puppeteer.page.target.md) | | |
| [title()](./puppeteer.page.title.md) | | |
| [type(selector, text, options)](./puppeteer.page.type.md) | | <p>Sends a <code>keydown</code>, <code>keypress/input</code>, and <code>keyup</code> event for each character in the text.</p><p>To press a special key, like <code>Control</code> or <code>ArrowDown</code>, use [Keyboard.press()](./puppeteer.keyboard.press.md).</p> |
| [url()](./puppeteer.page.url.md) | | |
| [viewport()](./puppeteer.page.viewport.md) | | |
| [waitForFileChooser(options)](./puppeteer.page.waitforfilechooser.md) | | <p>This method is typically coupled with an action that triggers file choosing.</p><p>:::caution</p><p>This must be called before the file chooser is launched. It will not return a currently active file chooser.</p><p>:::</p> |
| [waitForFrame(urlOrPredicate, options)](./puppeteer.page.waitforframe.md) | | |
| [waitForFunction(pageFunction, options, args)](./puppeteer.page.waitforfunction.md) | | Waits for a function to finish evaluating in the page's context. |
| [waitForNavigation(options)](./puppeteer.page.waitfornavigation.md) | | Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate. |
| [waitForNetworkIdle(options)](./puppeteer.page.waitfornetworkidle.md) | | |
| [waitForRequest(urlOrPredicate, options)](./puppeteer.page.waitforrequest.md) | | |
| [waitForResponse(urlOrPredicate, options)](./puppeteer.page.waitforresponse.md) | | |
| [waitForSelector(selector, options)](./puppeteer.page.waitforselector.md) | | <p>Wait for the <code>selector</code> to appear in page. If at the moment of calling the method the <code>selector</code> already exists, the method will return immediately. If the <code>selector</code> doesn't appear after the <code>timeout</code> milliseconds of waiting, the function will throw.</p><p>This method works across navigations:</p> |
| Method | Modifiers | Description |
| ------------------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [$(selector)](./puppeteer.page._.md) | | Runs <code>document.querySelector</code> within the page. If no element matches the selector, the return value resolves to <code>null</code>. |
| [$$(selector)](./puppeteer.page.__.md) | | The method runs <code>document.querySelectorAll</code> within the page. If no elements match the selector, the return value resolves to <code>[]</code>. |
| [$$eval(selector, pageFunction, args)](./puppeteer.page.__eval.md) | | This method runs <code>Array.from(document.querySelectorAll(selector))</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$eval(selector, pageFunction, args)](./puppeteer.page._eval.md) | | This method runs <code>document.querySelector</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
| [$x(expression)](./puppeteer.page._x.md) | | The method evaluates the XPath expression relative to the page document as its context node. If there are no such elements, the method resolves to an empty array. |
| [addScriptTag(options)](./puppeteer.page.addscripttag.md) | | Adds a <code>&lt;script&gt;</code> tag into the page with the desired URL or content. |
| [addStyleTag(options)](./puppeteer.page.addstyletag.md) | | Adds a <code>&lt;link rel=&quot;stylesheet&quot;&gt;</code> tag into the page with the desired URL or a <code>&lt;style type=&quot;text/css&quot;&gt;</code> tag with the content. |
| [authenticate(credentials)](./puppeteer.page.authenticate.md) | | Provide credentials for <code>HTTP authentication</code>. |
| [bringToFront()](./puppeteer.page.bringtofront.md) | | Brings page to front (activates tab). |
| [browser()](./puppeteer.page.browser.md) | | Get the browser the page belongs to. |
| [browserContext()](./puppeteer.page.browsercontext.md) | | Get the browser context that the page belongs to. |
| [click(selector, options)](./puppeteer.page.click.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to click in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [close(options)](./puppeteer.page.close.md) | | |
| [content()](./puppeteer.page.content.md) | | |
| [cookies(urls)](./puppeteer.page.cookies.md) | | If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned. |
| [createPDFStream(options)](./puppeteer.page.createpdfstream.md) | | Generates a PDF of the page with the <code>print</code> CSS media type. |
| [deleteCookie(cookies)](./puppeteer.page.deletecookie.md) | | |
| [emulate(options)](./puppeteer.page.emulate.md) | | Emulates given device metrics and user agent. |
| [emulateCPUThrottling(factor)](./puppeteer.page.emulatecputhrottling.md) | | Enables CPU throttling to emulate slow CPUs. |
| [emulateIdleState(overrides)](./puppeteer.page.emulateidlestate.md) | | Emulates the idle state. If no arguments set, clears idle state emulation. |
| [emulateMediaFeatures(features)](./puppeteer.page.emulatemediafeatures.md) | | |
| [emulateMediaType(type)](./puppeteer.page.emulatemediatype.md) | | |
| [emulateNetworkConditions(networkConditions)](./puppeteer.page.emulatenetworkconditions.md) | | |
| [emulateTimezone(timezoneId)](./puppeteer.page.emulatetimezone.md) | | |
| [emulateVisionDeficiency(type)](./puppeteer.page.emulatevisiondeficiency.md) | | Simulates the given vision deficiency on the page. |
| [evaluate(pageFunction, args)](./puppeteer.page.evaluate.md) | | <p>Evaluates a function in the page's context and returns the result.</p><p>If the function passed to <code>page.evaluteHandle</code> returns a Promise, the function will wait for the promise to resolve and return its value.</p> |
| [evaluateHandle(pageFunction, args)](./puppeteer.page.evaluatehandle.md) | | |
| [evaluateOnNewDocument(pageFunction, args)](./puppeteer.page.evaluateonnewdocument.md) | | <p>Adds a function which would be invoked in one of the following scenarios:</p><p>- whenever the page is navigated</p><p>- whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame.</p><p>The function is invoked 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 <code>Math.random</code>.</p> |
| [exposeFunction(name, pptrFunction)](./puppeteer.page.exposefunction.md) | | <p>The method adds a function called <code>name</code> on the page's <code>window</code> object. When called, the function executes <code>puppeteerFunction</code> in node.js and returns a <code>Promise</code> which resolves to the return value of <code>puppeteerFunction</code>.</p><p>If the puppeteerFunction returns a <code>Promise</code>, it will be awaited.</p><p>:::note</p><p>Functions installed via <code>page.exposeFunction</code> survive navigations.</p><p>:::note</p> |
| [focus(selector)](./puppeteer.page.focus.md) | | This method fetches an element with <code>selector</code> and focuses it. If there's no element matching <code>selector</code>, the method throws an error. |
| [frames()](./puppeteer.page.frames.md) | | |
| [goBack(options)](./puppeteer.page.goback.md) | | This method navigate to the previous page in history. |
| [goForward(options)](./puppeteer.page.goforward.md) | | This method navigate to the next page in history. |
| [goto(url, options)](./puppeteer.page.goto.md) | | |
| [hover(selector)](./puppeteer.page.hover.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [isClosed()](./puppeteer.page.isclosed.md) | | Indicates that the page has been closed. |
| [isDragInterceptionEnabled()](./puppeteer.page.isdraginterceptionenabled.md) | | |
| [isJavaScriptEnabled()](./puppeteer.page.isjavascriptenabled.md) | | |
| [mainFrame()](./puppeteer.page.mainframe.md) | | |
| [metrics()](./puppeteer.page.metrics.md) | | |
| [off(eventName, handler)](./puppeteer.page.off.md) | | |
| [on(eventName, handler)](./puppeteer.page.on.md) | | <p>Listen to page events.</p><p>:::note</p><p>This method exists to define event typings and handle proper wireup of cooperative request interception. Actual event listening and dispatching is delegated to [EventEmitter](./puppeteer.eventemitter.md).</p><p>:::</p> |
| [once(eventName, handler)](./puppeteer.page.once.md) | | |
| [pdf(options)](./puppeteer.page.pdf.md) | | |
| [queryObjects(prototypeHandle)](./puppeteer.page.queryobjects.md) | | This method iterates the JavaScript heap and finds all objects with the given prototype. |
| [reload(options)](./puppeteer.page.reload.md) | | |
| [screenshot(options)](./puppeteer.page.screenshot.md) | | |
| [select(selector, values)](./puppeteer.page.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. If there's no <code>&lt;select&gt;</code> element matching <code>selector</code>, the method throws an error. |
| [setBypassCSP(enabled)](./puppeteer.page.setbypasscsp.md) | | Toggles bypassing page's Content-Security-Policy. |
| [setCacheEnabled(enabled)](./puppeteer.page.setcacheenabled.md) | | Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled. |
| [setContent(html, options)](./puppeteer.page.setcontent.md) | | |
| [setCookie(cookies)](./puppeteer.page.setcookie.md) | | |
| [setDefaultNavigationTimeout(timeout)](./puppeteer.page.setdefaultnavigationtimeout.md) | | <p>This setting will change the default maximum navigation time for the following methods and related shortcuts:</p><p>- [page.goBack(options)](./puppeteer.page.goback.md)</p><p>- [page.goForward(options)](./puppeteer.page.goforward.md)</p><p>- [page.goto(url,options)](./puppeteer.page.goto.md)</p><p>- [page.reload(options)](./puppeteer.page.reload.md)</p><p>- [page.setContent(html,options)](./puppeteer.page.setcontent.md)</p><p>- [page.waitForNavigation(options)](./puppeteer.page.waitfornavigation.md)</p> |
| [setDefaultTimeout(timeout)](./puppeteer.page.setdefaulttimeout.md) | | |
| [setDragInterception(enabled)](./puppeteer.page.setdraginterception.md) | | |
| [setExtraHTTPHeaders(headers)](./puppeteer.page.setextrahttpheaders.md) | | <p>The extra HTTP headers will be sent with every request the page initiates.</p><p>:::tip</p><p>All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldnt impact your server code.)</p><p>:::</p><p>:::note</p><p>page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.</p><p>:::</p> |
| [setGeolocation(options)](./puppeteer.page.setgeolocation.md) | | Sets the page's geolocation. |
| [setJavaScriptEnabled(enabled)](./puppeteer.page.setjavascriptenabled.md) | | |
| [setOfflineMode(enabled)](./puppeteer.page.setofflinemode.md) | | |
| [setRequestInterception(value)](./puppeteer.page.setrequestinterception.md) | | <p>Activating request interception enables [HTTPRequest.abort()](./puppeteer.httprequest.abort.md), [HTTPRequest.continue()](./puppeteer.httprequest.continue.md) and [HTTPRequest.respond()](./puppeteer.httprequest.respond.md) methods. This provides the capability to modify network requests that are made by a page.</p><p>Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.</p><p>Enabling request interception disables page caching.</p><p>See the [Request interception guide](https://pptr.dev/next/guides/request-interception) for more details.</p> |
| [setUserAgent(userAgent, userAgentMetadata)](./puppeteer.page.setuseragent.md) | | |
| [setViewport(viewport)](./puppeteer.page.setviewport.md) | | <p><code>page.setViewport</code> will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.</p><p>In the case of multiple pages in a single browser, each page can have its own viewport size.</p> |
| [tap(selector)](./puppeteer.page.tap.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.touchscreen](./puppeteer.page.touchscreen.md) to tap in the center of the element. If there's no element matching <code>selector</code>, the method throws an error. |
| [target()](./puppeteer.page.target.md) | | |
| [title()](./puppeteer.page.title.md) | | |
| [type(selector, text, options)](./puppeteer.page.type.md) | | <p>Sends a <code>keydown</code>, <code>keypress/input</code>, and <code>keyup</code> event for each character in the text.</p><p>To press a special key, like <code>Control</code> or <code>ArrowDown</code>, use [Keyboard.press()](./puppeteer.keyboard.press.md).</p> |
| [url()](./puppeteer.page.url.md) | | |
| [viewport()](./puppeteer.page.viewport.md) | | |
| [waitForFileChooser(options)](./puppeteer.page.waitforfilechooser.md) | | <p>This method is typically coupled with an action that triggers file choosing.</p><p>:::caution</p><p>This must be called before the file chooser is launched. It will not return a currently active file chooser.</p><p>:::</p> |
| [waitForFrame(urlOrPredicate, options)](./puppeteer.page.waitforframe.md) | | |
| [waitForFunction(pageFunction, options, args)](./puppeteer.page.waitforfunction.md) | | Waits for a function to finish evaluating in the page's context. |
| [waitForNavigation(options)](./puppeteer.page.waitfornavigation.md) | | Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate. |
| [waitForNetworkIdle(options)](./puppeteer.page.waitfornetworkidle.md) | | |
| [waitForRequest(urlOrPredicate, options)](./puppeteer.page.waitforrequest.md) | | |
| [waitForResponse(urlOrPredicate, options)](./puppeteer.page.waitforresponse.md) | | |
| [waitForSelector(selector, options)](./puppeteer.page.waitforselector.md) | | <p>Wait for the <code>selector</code> to appear in page. If at the moment of calling the method the <code>selector</code> already exists, the method will return immediately. If the <code>selector</code> doesn't appear after the <code>timeout</code> milliseconds of waiting, the function will throw.</p><p>This method works across navigations:</p> |
```ts
const puppeteer = require('puppeteer');

View File

@ -46,4 +46,4 @@ Object containing metrics as key/value pairs.
## Remarks
NOTE: All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.

View File

@ -4,7 +4,19 @@ sidebar_label: Page.setExtraHTTPHeaders
# Page.setExtraHTTPHeaders() method
The extra HTTP headers will be sent with every request the page initiates. NOTE: All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldnt impact your server code.) NOTE: page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
The extra HTTP headers will be sent with every request the page initiates.
:::tip
All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldnt impact your server code.)
:::
:::note
page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
:::
**Signature:**

View File

@ -26,7 +26,7 @@ Promise&lt;void&gt;
## Remarks
NOTE: Consider using [BrowserContext.overridePermissions()](./puppeteer.browsercontext.overridepermissions.md) to grant permissions for the page to read its geolocation.
Consider using [BrowserContext.overridePermissions()](./puppeteer.browsercontext.overridepermissions.md) to grant permissions for the page to read its geolocation.
## Example

View File

@ -8,7 +8,7 @@ Activating request interception enables [HTTPRequest.abort()](./puppeteer.httpre
Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.
NOTE: Enabling request interception disables page caching.
Enabling request interception disables page caching.
See the [Request interception guide](https://pptr.dev/next/guides/request-interception) for more details.

View File

@ -20,4 +20,4 @@ all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/A
## Remarks
NOTE: This does not contain ServiceWorkers
This does not contain ServiceWorkers

View File

@ -4,7 +4,7 @@ sidebar_label: ScreenshotOptions.fullPage
# ScreenshotOptions.fullPage property
When true, takes a screenshot of the full page.
When `true`, takes a screenshot of the full page.
**Signature:**

View File

@ -18,7 +18,7 @@ export interface ScreenshotOptions
| [clip?](./puppeteer.screenshotoptions.clip.md) | | [ScreenshotClip](./puppeteer.screenshotclip.md) | <i>(Optional)</i> An object which specifies the clipping region of the page. |
| [encoding?](./puppeteer.screenshotoptions.encoding.md) | | 'base64' \| 'binary' | <i>(Optional)</i> Encoding of the image. |
| [fromSurface?](./puppeteer.screenshotoptions.fromsurface.md) | | boolean | <i>(Optional)</i> Capture the screenshot from the surface, rather than the view. |
| [fullPage?](./puppeteer.screenshotoptions.fullpage.md) | | boolean | <i>(Optional)</i> When true, takes a screenshot of the full page. |
| [fullPage?](./puppeteer.screenshotoptions.fullpage.md) | | boolean | <i>(Optional)</i> When <code>true</code>, takes a screenshot of the full page. |
| [omitBackground?](./puppeteer.screenshotoptions.omitbackground.md) | | boolean | <i>(Optional)</i> Hides default white background and allows capturing screenshots with transparency. |
| [path?](./puppeteer.screenshotoptions.path.md) | | string | <i>(Optional)</i> 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. If no path is provided, the image won't be saved to the disk. |
| [quality?](./puppeteer.screenshotoptions.quality.md) | | number | <i>(Optional)</i> Quality of the image, between 0-100. Not applicable to <code>png</code> images. |

View File

@ -12,7 +12,7 @@ export interface WaitForOptions
## Properties
| Property | Modifiers | Type | Description |
| ----------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| [timeout?](./puppeteer.waitforoptions.timeout.md) | | number | <i>(Optional)</i> Maximum wait time in milliseconds, defaults to 30 seconds, pass <code>0</code> to disable the timeout. |
| [waitUntil?](./puppeteer.waitforoptions.waituntil.md) | | [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)\[\] | <i>(Optional)</i> |
| Property | Modifiers | Type | Description |
| ----------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [timeout?](./puppeteer.waitforoptions.timeout.md) | | number | <p><i>(Optional)</i> Maximum wait time in milliseconds. Pass 0 to disable the timeout.</p><p>The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) or [Page.setDefaultNavigationTimeout()](./puppeteer.page.setdefaultnavigationtimeout.md) methods.</p> |
| [waitUntil?](./puppeteer.waitforoptions.waituntil.md) | | [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)\[\] | <i>(Optional)</i> |

View File

@ -4,7 +4,9 @@ sidebar_label: WaitForOptions.timeout
# WaitForOptions.timeout property
Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout.
Maximum wait time in milliseconds. Pass 0 to disable the timeout.
The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) or [Page.setDefaultNavigationTimeout()](./puppeteer.page.setdefaultnavigationtimeout.md) methods.
**Signature:**
@ -13,7 +15,3 @@ interface WaitForOptions {
timeout?: number;
}
```
## Remarks
The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) or [Page.setDefaultNavigationTimeout()](./puppeteer.page.setdefaultnavigationtimeout.md) methods.

View File

@ -4,6 +4,8 @@ sidebar_label: WaitForSelectorOptions.hidden
# WaitForSelectorOptions.hidden property
Wait for the selected element to not be found in the DOM or to be hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.
**Signature:**
```typescript

View File

@ -12,9 +12,9 @@ export interface WaitForSelectorOptions
## Properties
| Property | Modifiers | Type | Description |
| --------------------------------------------------------- | --------- | --------------------------------------------------------- | ----------------- |
| [hidden?](./puppeteer.waitforselectoroptions.hidden.md) | | boolean | <i>(Optional)</i> |
| [root?](./puppeteer.waitforselectoroptions.root.md) | | [ElementHandle](./puppeteer.elementhandle.md)&lt;Node&gt; | <i>(Optional)</i> |
| [timeout?](./puppeteer.waitforselectoroptions.timeout.md) | | number | <i>(Optional)</i> |
| [visible?](./puppeteer.waitforselectoroptions.visible.md) | | boolean | <i>(Optional)</i> |
| Property | Modifiers | Type | Description |
| --------------------------------------------------------- | --------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [hidden?](./puppeteer.waitforselectoroptions.hidden.md) | | boolean | <i>(Optional)</i> Wait for the selected element to not be found in the DOM or to be hidden, i.e. have <code>display: none</code> or <code>visibility: hidden</code> CSS properties. |
| [root?](./puppeteer.waitforselectoroptions.root.md) | | [ElementHandle](./puppeteer.elementhandle.md)&lt;Node&gt; | <i>(Optional)</i> |
| [timeout?](./puppeteer.waitforselectoroptions.timeout.md) | | number | <p><i>(Optional)</i> Maximum time to wait in milliseconds. Pass <code>0</code> to disable timeout.</p><p>The default value can be changed by using [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md)</p> |
| [visible?](./puppeteer.waitforselectoroptions.visible.md) | | boolean | <i>(Optional)</i> Wait for the selected element to be present in DOM and to be visible, i.e. to not have <code>display: none</code> or <code>visibility: hidden</code> CSS properties. |

View File

@ -4,6 +4,10 @@ sidebar_label: WaitForSelectorOptions.timeout
# WaitForSelectorOptions.timeout property
Maximum time to wait in milliseconds. Pass `0` to disable timeout.
The default value can be changed by using [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md)
**Signature:**
```typescript

View File

@ -4,6 +4,8 @@ sidebar_label: WaitForSelectorOptions.visible
# WaitForSelectorOptions.visible property
Wait for the selected element to be present in DOM and to be visible, i.e. to not have `display: none` or `visibility: hidden` CSS properties.
**Signature:**
```typescript

View File

@ -12,6 +12,6 @@ export interface WaitTimeoutOptions
## Properties
| Property | Modifiers | Type | Description |
| ----------------------------------------------------- | --------- | ------ | ------------------------------------------------------------------------------------------------------------------------ |
| [timeout?](./puppeteer.waittimeoutoptions.timeout.md) | | number | <i>(Optional)</i> Maximum wait time in milliseconds, defaults to 30 seconds, pass <code>0</code> to disable the timeout. |
| Property | Modifiers | Type | Description |
| ----------------------------------------------------- | --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [timeout?](./puppeteer.waittimeoutoptions.timeout.md) | | number | <p><i>(Optional)</i> Maximum wait time in milliseconds. Pass 0 to disable the timeout.</p><p>The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) method.</p> |

View File

@ -4,7 +4,9 @@ sidebar_label: WaitTimeoutOptions.timeout
# WaitTimeoutOptions.timeout property
Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout.
Maximum wait time in milliseconds. Pass 0 to disable the timeout.
The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) method.
**Signature:**
@ -13,7 +15,3 @@ interface WaitTimeoutOptions {
timeout?: number;
}
```
## Remarks
The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) method.

View File

@ -4,7 +4,7 @@ sidebar_label: WebWorker
# WebWorker class
The WebWorker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
This class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
**Signature:**

View File

@ -176,7 +176,6 @@ export class Accessibility {
* ```
*
* @returns An AXNode object representing the snapshot.
*
*/
public async snapshot(
options: SnapshotOptions = {}

View File

@ -112,7 +112,7 @@ const waitFor = async (
const binding: PageBinding = {
name: 'ariaQuerySelector',
pptrFunction: async (selector: string) => {
const root = options.root || (await isolatedWorld._document());
const root = options.root || (await isolatedWorld.document());
const element = await queryOne(root, selector);
return element;
},

View File

@ -1,9 +1,13 @@
import {Protocol} from 'devtools-protocol';
import {assert} from './assert.js';
import {CDPSession} from './Connection.js';
import {WaitForSelectorOptions} from './IsolatedWorld.js';
import {ExecutionContext} from './ExecutionContext.js';
import {Frame, FrameManager} from './FrameManager.js';
import {
MAIN_WORLD,
PUPPETEER_WORLD,
WaitForSelectorOptions,
} from './IsolatedWorld.js';
import {
BoundingBox,
BoxModel,
@ -88,34 +92,186 @@ export class ElementHandle<
}
/**
* Wait for the `selector` to appear within the element. If at the moment of calling the
* method the `selector` already exists, the method will return immediately. If
* the `selector` doesn't appear after the `timeout` milliseconds of waiting, the
* function will throw.
* Queries the current element for an element matching the given selector.
*
* This method does not work across navigations or if the element is detached from DOM.
* @param selector - The selector to query for.
* @returns A {@link ElementHandle | element handle} to the first element
* matching the given selector. Otherwise, `null`.
*/
async $<Selector extends string>(
selector: Selector
): Promise<ElementHandle<NodeFor<Selector>> | null> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(
queryHandler.queryOne,
'Cannot handle queries for a single element with the given selector'
);
return (await queryHandler.queryOne(
this,
updatedSelector
)) as ElementHandle<NodeFor<Selector>> | null;
}
/**
* Queries the current element for all elements matching the given selector.
*
* @param selector - A
* {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
* of an element to wait for
* @param options - Optional waiting parameters
* @returns Promise which resolves when element specified by selector string
* is added to DOM. Resolves to `null` if waiting for hidden: `true` and
* selector is not found in DOM.
* @remarks
* The optional parameters in `options` are:
* @param selector - The selector to query for.
* @returns An array of {@link ElementHandle | element handles} that point to
* elements matching the given selector.
*/
async $$<Selector extends string>(
selector: Selector
): Promise<Array<ElementHandle<NodeFor<Selector>>>> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(
queryHandler.queryAll,
'Cannot handle queries for a multiple element with the given selector'
);
return (await queryHandler.queryAll(this, updatedSelector)) as Array<
ElementHandle<NodeFor<Selector>>
>;
}
/**
* Runs the given function on the first element matching the given selector in
* the current element.
*
* - `visible`: wait for the selected element to be present in DOM and to be
* visible, i.e. to not have `display: none` or `visibility: hidden` CSS
* properties. Defaults to `false`.
* If the given function returns a promise, then this method will wait till
* the promise resolves.
*
* - `hidden`: wait for the selected element to not be found in the DOM or to be hidden,
* i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to
* `false`.
* @example
* ```ts
* const tweetHandle = await page.$('.tweet');
* expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
* expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
* ```
*
* - `timeout`: maximum time to wait in milliseconds. Defaults to `30000`
* (30 seconds). Pass `0` to disable timeout. The default value can be changed
* by using the {@link Page.setDefaultTimeout} method.
* @param selector - The selector to query for.
* @param pageFunction - The function to be evaluated in this element's page's
* context. The first element matching the selector will be passed in as the
* first argument.
* @param args - Additional arguments to pass to `pageFunction`.
* @returns A promise to the result of the function.
*/
async $eval<
Selector extends string,
Params extends unknown[],
Func extends EvaluateFunc<
[ElementHandle<NodeFor<Selector>>, ...Params]
> = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...Params]>
>(
selector: Selector,
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>> {
const elementHandle = await this.$(selector);
if (!elementHandle) {
throw new Error(
`Error: failed to find element matching selector "${selector}"`
);
}
const result = await elementHandle.evaluate(pageFunction, ...args);
await elementHandle.dispose();
return result;
}
/**
* Runs the given function on an array of elements matching the given selector
* in the current element.
*
* If the given function returns a promise, then this method will wait till
* the promise resolves.
*
* @example
* HTML:
* ```html
* <div class="feed">
* <div class="tweet">Hello!</div>
* <div class="tweet">Hi!</div>
* </div>
* ```
* JavaScript:
* ```js
* const feedHandle = await page.$('.feed');
* expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)))
* .toEqual(['Hello!', 'Hi!']);
* ```
*
* @param selector - The selector to query for.
* @param pageFunction - The function to be evaluated in the element's page's
* context. An array of elements matching the given selector will be passed to
* the function as its first argument.
* @param args - Additional arguments to pass to `pageFunction`.
* @returns A promise to the result of the function.
*/
async $$eval<
Selector extends string,
Params extends unknown[],
Func extends EvaluateFunc<
[Array<NodeFor<Selector>>, ...Params]
> = EvaluateFunc<[Array<NodeFor<Selector>>, ...Params]>
>(
selector: Selector,
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(queryHandler.queryAllArray);
const arrayHandle = (await queryHandler.queryAllArray(
this,
updatedSelector
)) as JSHandle<Array<NodeFor<Selector>>>;
const result = await arrayHandle.evaluate(pageFunction, ...args);
await arrayHandle.dispose();
return result;
}
/**
* @deprecated Use {@link ElementHandle.$$} with the `xpath` prefix.
*
* The method evaluates the XPath expression relative to the elementHandle.
* If there are no such elements, the method will resolve to an empty array.
* @param expression - Expression to {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate | evaluate}
*/
async $x(expression: string): Promise<Array<ElementHandle<Node>>> {
if (expression.startsWith('//')) {
expression = `.${expression}`;
}
return this.$$(`xpath/${expression}`);
}
/**
* Wait for an element matching the given selector to appear in the current
* element.
*
* Unlike {@link Frame.waitForSelector}, this method does not work across
* navigations or if the element is detached from DOM.
*
* @example
* ```ts
* const puppeteer = require('puppeteer');
*
* (async () => {
* const browser = await puppeteer.launch();
* const page = await browser.newPage();
* let currentURL;
* page.mainFrame()
* .waitForSelector('img')
* .then(() => console.log('First URL with image: ' + currentURL));
*
* for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* }
* await browser.close();
* })();
* ```
* @param selector - The selector to query and wait for.
* @param options - Options for customizing waiting behavior.
* @returns An element matching the given selector.
* @throws Throws if an element matching the given selector doesn't appear.
*/
async waitForSelector<Selector extends string>(
selector: Selector,
@ -123,16 +279,19 @@ export class ElementHandle<
): Promise<ElementHandle<NodeFor<Selector>> | null> {
const frame = this._context.frame();
assert(frame);
const adoptedRoot = await frame._secondaryWorld.adoptHandle(this);
const handle = await frame._secondaryWorld.waitForSelector(selector, {
...options,
root: adoptedRoot,
});
const adoptedRoot = await frame.worlds[PUPPETEER_WORLD].adoptHandle(this);
const handle = await frame.worlds[PUPPETEER_WORLD].waitForSelector(
selector,
{
...options,
root: adoptedRoot,
}
);
await adoptedRoot.dispose();
if (!handle) {
return null;
}
const result = (await frame._mainWorld.adoptHandle(
const result = (await frame.worlds[MAIN_WORLD].adoptHandle(
handle
)) as ElementHandle<NodeFor<Selector>>;
await handle.dispose();
@ -140,14 +299,16 @@ export class ElementHandle<
}
/**
* @deprecated Use {@link ElementHandle.waitForSelector} with the `xpath` prefix.
* @deprecated Use {@link ElementHandle.waitForSelector} with the `xpath`
* prefix.
*
* Wait for the `xpath` within the element. If at the moment of calling the
* method the `xpath` already exists, the method will return immediately. If
* the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the
* function will throw.
*
* If `xpath` starts with `//` instead of `.//`, the dot will be appended automatically.
* If `xpath` starts with `//` instead of `.//`, the dot will be appended
* automatically.
*
* This method works across navigation
* ```ts
@ -180,16 +341,17 @@ export class ElementHandle<
* The optional Argument `options` have properties:
*
* - `visible`: A boolean to wait for element to be present in DOM and to be
* visible, i.e. to not have `display: none` or `visibility: hidden` CSS
* properties. Defaults to `false`.
* visible, i.e. to not have `display: none` or `visibility: hidden` CSS
* properties. Defaults to `false`.
*
* - `hidden`: A boolean wait for element to not be found in the DOM or to be
* hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.
* Defaults to `false`.
* hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.
* Defaults to `false`.
*
* - `timeout`: A number which is 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 {@link Page.setDefaultTimeout} method.
* Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
* default value can be changed by using the {@link Page.setDefaultTimeout}
* method.
*/
async waitForXPath(
xpath: string,
@ -818,150 +980,6 @@ export class ElementHandle<
return imageData;
}
/**
* Runs `element.querySelector` within the page.
*
* @param selector - The selector to query with.
* @returns `null` if no element matches the selector.
* @throws `Error` if the selector has no associated query handler.
*/
async $<Selector extends string>(
selector: Selector
): Promise<ElementHandle<NodeFor<Selector>> | null> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(
queryHandler.queryOne,
'Cannot handle queries for a single element with the given selector'
);
return (await queryHandler.queryOne(
this,
updatedSelector
)) as ElementHandle<NodeFor<Selector>> | null;
}
/**
* Runs `element.querySelectorAll` within the page. If no elements match the selector,
* the return value resolves to `[]`.
*/
/**
* Runs `element.querySelectorAll` within the page.
*
* @param selector - The selector to query with.
* @returns `[]` if no element matches the selector.
* @throws `Error` if the selector has no associated query handler.
*/
async $$<Selector extends string>(
selector: Selector
): Promise<Array<ElementHandle<NodeFor<Selector>>>> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(
queryHandler.queryAll,
'Cannot handle queries for a multiple element with the given selector'
);
return (await queryHandler.queryAll(this, updatedSelector)) as Array<
ElementHandle<NodeFor<Selector>>
>;
}
/**
* This method runs `document.querySelector` within the element and passes it as
* the first argument to `pageFunction`. If there's no element matching `selector`,
* the method throws an error.
*
* If `pageFunction` returns a Promise, then `frame.$eval` would wait for the promise
* to resolve and return its value.
*
* @example
* ```ts
* const tweetHandle = await page.$('.tweet');
* expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
* expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
* ```
*/
async $eval<
Selector extends string,
Params extends unknown[],
Func extends EvaluateFunc<
[ElementHandle<NodeFor<Selector>>, ...Params]
> = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...Params]>
>(
selector: Selector,
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>> {
const elementHandle = await this.$(selector);
if (!elementHandle) {
throw new Error(
`Error: failed to find element matching selector "${selector}"`
);
}
const result = await elementHandle.evaluate(pageFunction, ...args);
await elementHandle.dispose();
return result;
}
/**
* This method runs `document.querySelectorAll` within the element and passes it as
* the first argument to `pageFunction`. If there's no element matching `selector`,
* the method throws an error.
*
* If `pageFunction` returns a Promise, then `frame.$$eval` would wait for the
* promise to resolve and return its value.
*
* @example
* ```html
* <div class="feed">
* <div class="tweet">Hello!</div>
* <div class="tweet">Hi!</div>
* </div>
* ```
*
* @example
* ```ts
* const feedHandle = await page.$('.feed');
* expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)))
* .toEqual(['Hello!', 'Hi!']);
* ```
*/
async $$eval<
Selector extends string,
Params extends unknown[],
Func extends EvaluateFunc<
[Array<NodeFor<Selector>>, ...Params]
> = EvaluateFunc<[Array<NodeFor<Selector>>, ...Params]>
>(
selector: Selector,
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(queryHandler.queryAllArray);
const arrayHandle = (await queryHandler.queryAllArray(
this,
updatedSelector
)) as JSHandle<Array<NodeFor<Selector>>>;
const result = await arrayHandle.evaluate(pageFunction, ...args);
await arrayHandle.dispose();
return result;
}
/**
* @deprecated Use {@link ElementHandle.$$} with the `xpath` prefix.
*
* The method evaluates the XPath expression relative to the elementHandle.
* If there are no such elements, the method will resolve to an empty array.
* @param expression - Expression to {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate | evaluate}
*/
async $x(expression: string): Promise<Array<ElementHandle<Node>>> {
if (expression.startsWith('//')) {
expression = `.${expression}`;
}
return this.$$(`xpath/${expression}`);
}
/**
* Resolves to true if the element is visible in the current viewport.
*/

View File

@ -20,10 +20,15 @@ import {ElementHandle} from './ElementHandle.js';
/**
* File choosers let you react to the page requesting for a file.
*
* @remarks
* `FileChooser` objects are returned via the `page.waitForFileChooser` method.
* `FileChooser` instances are returned via the {@link Page.waitForFileChooser} method.
*
* In browsers, only one file chooser can be opened at a time.
* All file choosers must be accepted or canceled. Not doing so will prevent
* subsequent file choosers from appearing.
*
* @example
* An example of using `FileChooser`:
* ```ts
* const [fileChooser] = await Promise.all([
* page.waitForFileChooser(),
@ -31,9 +36,7 @@ import {ElementHandle} from './ElementHandle.js';
* ]);
* await fileChooser.accept(['/tmp/myfile.pdf']);
* ```
* **NOTE** In browsers, only one file chooser can be opened at a time.
* All file choosers must be accepted or canceled. Not doing so will prevent
* subsequent file choosers from appearing.
*
* @public
*/
export class FileChooser {
@ -53,7 +56,9 @@ export class FileChooser {
}
/**
* Whether file chooser allow for {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple | multiple} file selection.
* Whether file chooser allow for
* {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple | multiple}
* file selection.
*/
isMultiple(): boolean {
return this.#multiple;
@ -61,8 +66,10 @@ export class FileChooser {
/**
* Accept the file chooser request with given paths.
* @param filePaths - If some of the `filePaths` are relative paths,
* then they are resolved relative to the {@link https://nodejs.org/api/process.html#process_process_cwd | current working directory}.
*
* @param filePaths - If some of the `filePaths` are relative paths, then
* they are resolved relative to the
* {@link https://nodejs.org/api/process.html#process_process_cwd | current working directory}.
*/
async accept(filePaths: string[]): Promise<void> {
assert(

File diff suppressed because it is too large Load Diff

View File

@ -55,8 +55,27 @@ declare const checkWaitForOptions: (
* @public
*/
export interface WaitForSelectorOptions {
/**
* Wait for the selected element to be present in DOM and to be visible, i.e.
* to not have `display: none` or `visibility: hidden` CSS properties.
*
* @defaultValue `false`
*/
visible?: boolean;
/**
* Wait for the selected element to not be found in the DOM or to be hidden,
* i.e. have `display: none` or `visibility: hidden` CSS properties.
*
* @defaultValue `false`
*/
hidden?: boolean;
/**
* Maximum time to wait in milliseconds. Pass `0` to disable timeout.
*
* The default value can be changed by using {@link Page.setDefaultTimeout}
*
* @defaultValue `30000` (30 seconds)
*/
timeout?: number;
root?: ElementHandle<Node>;
}
@ -69,6 +88,29 @@ export interface PageBinding {
pptrFunction: Function;
}
/**
* A unique key for {@link IsolatedWorldChart} to denote the default world.
* Execution contexts are automatically created in the default world.
*
* @internal
*/
export const MAIN_WORLD = Symbol('mainWorld');
/**
* A unique key for {@link IsolatedWorldChart} to denote the puppeteer world.
* This world contains all puppeteer-internal bindings/code.
*
* @internal
*/
export const PUPPETEER_WORLD = Symbol('puppeteerWorld');
/**
* @internal
*/
export interface IsolatedWorldChart {
[key: string]: IsolatedWorld;
[MAIN_WORLD]: IsolatedWorld;
[PUPPETEER_WORLD]: IsolatedWorld;
}
/**
* @internal
*/
@ -187,19 +229,18 @@ export class IsolatedWorld {
async $<Selector extends string>(
selector: Selector
): Promise<ElementHandle<NodeFor<Selector>> | null> {
const document = await this._document();
const value = await document.$(selector);
return value;
const document = await this.document();
return document.$(selector);
}
async $$<Selector extends string>(
selector: Selector
): Promise<Array<ElementHandle<NodeFor<Selector>>>> {
const document = await this._document();
const document = await this.document();
return document.$$(selector);
}
async _document(): Promise<ElementHandle<Document>> {
async document(): Promise<ElementHandle<Document>> {
if (this.#documentPromise) {
return this.#documentPromise;
}
@ -212,9 +253,8 @@ export class IsolatedWorld {
}
async $x(expression: string): Promise<Array<ElementHandle<Node>>> {
const document = await this._document();
const value = await document.$x(expression);
return value;
const document = await this.document();
return document.$x(expression);
}
async $eval<
@ -228,7 +268,7 @@ export class IsolatedWorld {
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>> {
const document = await this._document();
const document = await this.document();
return document.$eval(selector, pageFunction, ...args);
}
@ -243,9 +283,22 @@ export class IsolatedWorld {
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>> {
const document = await this._document();
const value = await document.$$eval(selector, pageFunction, ...args);
return value;
const document = await this.document();
return document.$$eval(selector, pageFunction, ...args);
}
async waitForSelector<Selector extends string>(
selector: Selector,
options: WaitForSelectorOptions
): Promise<ElementHandle<NodeFor<Selector>> | null> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(queryHandler.waitFor, 'Query handler does not support waiting');
return (await queryHandler.waitFor(
this,
updatedSelector,
options
)) as ElementHandle<NodeFor<Selector>> | null;
}
async content(): Promise<string> {
@ -299,7 +352,6 @@ export class IsolatedWorld {
* Adds a script tag into the current context.
*
* @remarks
*
* You can pass a URL, filepath or string of contents. Note that when running Puppeteer
* in a browser environment you cannot pass a filepath and should use either
* `url` or `content`.
@ -399,27 +451,23 @@ export class IsolatedWorld {
* Adds a style tag into the current context.
*
* @remarks
*
* You can pass a URL, filepath or string of contents. Note that when running Puppeteer
* in a browser environment you cannot pass a filepath and should use either
* `url` or `content`.
*
*/
async addStyleTag(options: {
url?: string;
path?: string;
content?: string;
}): Promise<ElementHandle<Node>> {
}): Promise<ElementHandle<HTMLStyleElement | HTMLLinkElement>> {
const {url = null, path = null, content = null} = options;
if (url !== null) {
try {
const context = await this.executionContext();
const handle = await context.evaluateHandle(addStyleUrl, url);
const elementHandle = handle.asElement();
if (elementHandle === null) {
throw new Error('Style element is not found');
}
return elementHandle;
return (await context.evaluateHandle(
addStyleUrl,
url
)) as ElementHandle<HTMLLinkElement>;
} catch (error) {
throw new Error(`Loading style from ${url} failed`);
}
@ -441,22 +489,18 @@ export class IsolatedWorld {
let contents = await fs.readFile(path, 'utf8');
contents += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/';
const context = await this.executionContext();
const handle = await context.evaluateHandle(addStyleContent, contents);
const elementHandle = handle.asElement();
if (elementHandle === null) {
throw new Error('Style element is not found');
}
return elementHandle;
return (await context.evaluateHandle(
addStyleContent,
contents
)) as ElementHandle<HTMLStyleElement>;
}
if (content !== null) {
const context = await this.executionContext();
const handle = await context.evaluateHandle(addStyleContent, content);
const elementHandle = handle.asElement();
if (elementHandle === null) {
throw new Error('Style element is not found');
}
return elementHandle;
return (await context.evaluateHandle(
addStyleContent,
content
)) as ElementHandle<HTMLStyleElement>;
}
throw new Error(
@ -539,20 +583,6 @@ export class IsolatedWorld {
await handle.dispose();
}
async waitForSelector<Selector extends string>(
selector: Selector,
options: WaitForSelectorOptions
): Promise<ElementHandle<NodeFor<Selector>> | null> {
const {updatedSelector, queryHandler} =
getQueryHandlerAndSelector(selector);
assert(queryHandler.waitFor, 'Query handler does not support waiting');
return (await queryHandler.waitFor(
this,
updatedSelector,
options
)) as ElementHandle<NodeFor<Selector>> | null;
}
// If multiple waitFor are set up asynchronously, we need to wait for the
// first one to set up the binding in the page before running the others.
#settingUpBinding: Promise<void> | null = null;

View File

@ -127,7 +127,7 @@ export class LifecycleWatcher {
this.#timeout = timeout;
this.#eventListeners = [
addEventListener(
frameManager._client,
frameManager.client,
CDPSessionEmittedEvents.Disconnected,
this.#terminate.bind(
this,
@ -160,12 +160,12 @@ export class LifecycleWatcher {
this.#onFrameDetached.bind(this)
),
addEventListener(
this.#frameManager.networkManager(),
this.#frameManager.networkManager,
NetworkManagerEmittedEvents.Request,
this.#onRequest.bind(this)
),
addEventListener(
this.#frameManager.networkManager(),
this.#frameManager.networkManager,
NetworkManagerEmittedEvents.Response,
this.#onResponse.bind(this)
),

View File

@ -23,7 +23,7 @@ import {CDPSession, CDPSessionEmittedEvents} from './Connection.js';
import {ConsoleMessage, ConsoleMessageType} from './ConsoleMessage.js';
import {Coverage} from './Coverage.js';
import {Dialog} from './Dialog.js';
import {WaitForSelectorOptions} from './IsolatedWorld.js';
import {MAIN_WORLD, WaitForSelectorOptions} from './IsolatedWorld.js';
import {ElementHandle} from './ElementHandle.js';
import {EmulationManager} from './EmulationManager.js';
import {EventEmitter, Handler} from './EventEmitter.js';
@ -70,6 +70,8 @@ import {
valueFromRemoteObject,
waitForEvent,
waitWithTimeout,
createDeferredPromiseWithTimer,
DeferredPromise,
} from './util.js';
import {WebWorker} from './WebWorker.js';
@ -97,12 +99,12 @@ export interface Metrics {
*/
export interface WaitTimeoutOptions {
/**
* Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to
* disable the timeout.
* Maximum wait time in milliseconds. Pass 0 to disable the timeout.
*
* @remarks
* The default value can be changed by using the
* {@link Page.setDefaultTimeout} method.
*
* @defaultValue `30000`
*/
timeout?: number;
}
@ -112,13 +114,13 @@ export interface WaitTimeoutOptions {
*/
export interface WaitForOptions {
/**
* Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to
* disable the timeout.
* Maximum wait time in milliseconds. Pass 0 to disable the timeout.
*
* @remarks
* The default value can be changed by using the
* {@link Page.setDefaultTimeout} or {@link Page.setDefaultNavigationTimeout}
* methods.
*
* @defaultValue `30000`
*/
timeout?: number;
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
@ -129,11 +131,11 @@ export interface WaitForOptions {
*/
export interface GeolocationOptions {
/**
* Latitude between -90 and 90.
* Latitude between `-90` and `90`.
*/
longitude: number;
/**
* Longitude between -180 and 180.
* Longitude between `-180` and `180`.
*/
latitude: number;
/**
@ -165,7 +167,7 @@ export interface ScreenshotClip {
*/
export interface ScreenshotOptions {
/**
* @defaultValue 'png'
* @defaultValue `png`
*/
type?: 'png' | 'jpeg' | 'webp';
/**
@ -176,8 +178,8 @@ export interface ScreenshotOptions {
*/
path?: string;
/**
* When true, takes a screenshot of the full page.
* @defaultValue false
* When `true`, takes a screenshot of the full page.
* @defaultValue `false`
*/
fullPage?: boolean;
/**
@ -190,22 +192,22 @@ export interface ScreenshotOptions {
quality?: number;
/**
* Hides default white background and allows capturing screenshots with transparency.
* @defaultValue false
* @defaultValue `false`
*/
omitBackground?: boolean;
/**
* Encoding of the image.
* @defaultValue 'binary'
* @defaultValue `binary`
*/
encoding?: 'base64' | 'binary';
/**
* Capture the screenshot beyond the viewport.
* @defaultValue true
* @defaultValue `true`
*/
captureBeyondViewport?: boolean;
/**
* Capture the screenshot from the surface, rather than the view.
* @defaultValue true
* @defaultValue `true`
*/
fromSurface?: boolean;
}
@ -216,7 +218,8 @@ export interface ScreenshotOptions {
* @public
*/
export const enum PageEmittedEvents {
/** Emitted when the page closes.
/**
* Emitted when the page closes.
* @eventProperty
*/
Close = 'close',
@ -283,8 +286,8 @@ export const enum PageEmittedEvents {
*/
Metrics = 'metrics',
/**
* Emitted when an uncaught exception happens within the page.
* Contains an `Error`.
* Emitted when an uncaught exception happens within the page. Contains an
* `Error`.
*/
PageError = 'pageerror',
/**
@ -294,31 +297,32 @@ export const enum PageEmittedEvents {
*
* @example
*
* ```ts
* const [popup] = await Promise.all([
* new Promise(resolve => page.once('popup', resolve)),
* page.click('a[target=_blank]'),
* ]);
* ```
*```ts
*const [popup] = await Promise.all([
* new Promise(resolve => page.once('popup', resolve)),
* page.click('a[target=_blank]'),
*]);
*```
*
* ```ts
* const [popup] = await Promise.all([
* new Promise(resolve => page.once('popup', resolve)),
* page.evaluate(() => window.open('https://example.com')),
* ]);
* ```
*```ts
*const [popup] = await Promise.all([
* new Promise(resolve => page.once('popup', resolve)),
* page.evaluate(() => window.open('https://example.com')),
*]);
*```
*/
Popup = 'popup',
/**
* Emitted when a page issues a request and contains a {@link HTTPRequest}.
*
* @remarks
* The object is readonly. See {@link Page.setRequestInterception} for intercepting
* and mutating requests.
* The object is readonly. See {@link Page.setRequestInterception} for
* intercepting and mutating requests.
*/
Request = 'request',
/**
* Emitted when a request ended up loading from cache. Contains a {@link HTTPRequest}.
* Emitted when a request ended up loading from cache. Contains a
* {@link HTTPRequest}.
*
* @remarks
* For certain requests, might contain undefined.
@ -337,7 +341,8 @@ export const enum PageEmittedEvents {
*/
RequestFailed = 'requestfailed',
/**
* Emitted when a request finishes successfully. Contains a {@link HTTPRequest}.
* Emitted when a request finishes successfully. Contains a
* {@link HTTPRequest}.
*/
RequestFinished = 'requestfinished',
/**
@ -363,6 +368,7 @@ export const enum PageEmittedEvents {
*
* See {@link PageEmittedEvents} for more detail on the events and when they are
* emitted.
*
* @public
*/
export interface PageEventObject {
@ -475,7 +481,7 @@ export class Page extends EventEmitter {
#viewport: Viewport | null;
#screenshotTaskQueue: TaskQueue;
#workers = new Map<string, WebWorker>();
#fileChooserInterceptors = new Set<(chooser: FileChooser) => void>();
#fileChooserPromises = new Set<DeferredPromise<FileChooser>>();
#disconnectPromise?: Promise<Error>;
#userDragInterceptionEnabled = false;
@ -527,7 +533,7 @@ export class Page extends EventEmitter {
return this.emit(PageEmittedEvents.FrameNavigated, event);
});
const networkManager = this.#frameManager.networkManager();
const networkManager = this.#frameManager.networkManager;
networkManager.on(NetworkManagerEmittedEvents.Request, event => {
return this.emit(PageEmittedEvents.Request, event);
});
@ -546,7 +552,6 @@ export class Page extends EventEmitter {
networkManager.on(NetworkManagerEmittedEvents.RequestFinished, event => {
return this.emit(PageEmittedEvents.RequestFinished, event);
});
this.#fileChooserInterceptors = new Set();
client.on('Page.domContentEventFired', () => {
return this.emit(PageEmittedEvents.DOMContentLoaded);
@ -605,7 +610,7 @@ export class Page extends EventEmitter {
};
#onAttachedToTarget = async (createdTarget: Target) => {
await this.#frameManager.onAttachedToTarget(createdTarget);
this.#frameManager.onAttachedToTarget(createdTarget);
if (createdTarget._getTargetInfo().type === 'worker') {
const session = createdTarget._session();
assert(session);
@ -639,21 +644,23 @@ export class Page extends EventEmitter {
async #onFileChooser(
event: Protocol.Page.FileChooserOpenedEvent
): Promise<void> {
if (!this.#fileChooserInterceptors.size) {
if (!this.#fileChooserPromises.size) {
return;
}
const frame = this.#frameManager.frame(event.frameId);
assert(frame);
assert(frame, 'This should never happen.');
// This is guaranteed to be an HTMLInputElement handle by the event.
const handle = (await frame._mainWorld.adoptBackendNode(
const handle = (await frame.worlds[MAIN_WORLD].adoptBackendNode(
event.backendNodeId
)) as ElementHandle<HTMLInputElement>;
const interceptors = Array.from(this.#fileChooserInterceptors);
this.#fileChooserInterceptors.clear();
const fileChooser = new FileChooser(handle, event);
for (const interceptor of interceptors) {
interceptor.call(undefined, fileChooser);
for (const promise of this.#fileChooserPromises) {
promise.resolve(fileChooser);
}
this.#fileChooserPromises.clear();
}
/**
@ -666,7 +673,7 @@ export class Page extends EventEmitter {
/**
* @returns `true` if the page has JavaScript enabled, `false` otherwise.
*/
public isJavaScriptEnabled(): boolean {
isJavaScriptEnabled(): boolean {
return this.#javascriptEnabled;
}
@ -681,7 +688,7 @@ export class Page extends EventEmitter {
*
* :::
*/
public override on<K extends keyof PageEventObject>(
override on<K extends keyof PageEventObject>(
eventName: K,
handler: (event: PageEventObject[K]) => void
): EventEmitter {
@ -701,7 +708,7 @@ export class Page extends EventEmitter {
return super.on(eventName, handler);
}
public override once<K extends keyof PageEventObject>(
override once<K extends keyof PageEventObject>(
eventName: K,
handler: (event: PageEventObject[K]) => void
): EventEmitter {
@ -752,33 +759,30 @@ export class Page extends EventEmitter {
async waitForFileChooser(
options: WaitTimeoutOptions = {}
): Promise<FileChooser> {
if (!this.#fileChooserInterceptors.size) {
if (!this.#fileChooserPromises.size) {
await this.#client.send('Page.setInterceptFileChooserDialog', {
enabled: true,
});
}
const {timeout = this.#timeoutSettings.timeout()} = options;
let callback!: (value: FileChooser) => void;
const promise = new Promise<FileChooser>(x => {
return (callback = x);
});
this.#fileChooserInterceptors.add(callback);
return waitWithTimeout<FileChooser>(
promise,
'waiting for file chooser',
timeout
).catch(error => {
this.#fileChooserInterceptors.delete(callback);
const promise = createDeferredPromiseWithTimer<FileChooser>(
`Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`
);
this.#fileChooserPromises.add(promise);
return promise.catch(error => {
this.#fileChooserPromises.delete(promise);
throw error;
});
}
/**
* Sets the page's geolocation.
*
* @remarks
* NOTE: Consider using {@link BrowserContext.overridePermissions} to grant
* Consider using {@link BrowserContext.overridePermissions} to grant
* permissions for the page to read its geolocation.
*
* @example
* ```ts
* await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
@ -857,6 +861,7 @@ export class Page extends EventEmitter {
/**
* @returns The page's main frame.
*
* @remarks
* Page is guaranteed to have a main frame which persists during navigations.
*/
@ -892,12 +897,12 @@ export class Page extends EventEmitter {
}
/**
* @returns all of the dedicated
* {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API |
* WebWorkers}
* associated with the page.
* @returns all of the dedicated {@link
* https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API |
* WebWorkers} associated with the page.
*
* @remarks
* NOTE: This does not contain ServiceWorkers
* This does not contain ServiceWorkers
*/
workers(): WebWorker[] {
return Array.from(this.#workers.values());
@ -911,9 +916,11 @@ export class Page extends EventEmitter {
* Once request interception is enabled, every request will stall unless it's
* continued, responded or aborted; or completed using the browser cache.
*
* NOTE: Enabling request interception disables page caching.
* Enabling request interception disables page caching.
*
* See the {@link https://pptr.dev/next/guides/request-interception|Request interception guide} for more details.
* See the
* {@link https://pptr.dev/next/guides/request-interception|Request interception guide}
* for more details.
*
* @example
* An example of a naïve request interceptor that aborts all image requests:
@ -938,7 +945,7 @@ export class Page extends EventEmitter {
* @param value - Whether to enable request interception.
*/
async setRequestInterception(value: boolean): Promise<void> {
return this.#frameManager.networkManager().setRequestInterception(value);
return this.#frameManager.networkManager.setRequestInterception(value);
}
/**
@ -962,7 +969,7 @@ export class Page extends EventEmitter {
* (#pageemulatenetworkconditionsnetworkconditions)
*/
setOfflineMode(enabled: boolean): Promise<void> {
return this.#frameManager.networkManager().setOfflineMode(enabled);
return this.#frameManager.networkManager.setOfflineMode(enabled);
}
/**
@ -989,9 +996,9 @@ export class Page extends EventEmitter {
emulateNetworkConditions(
networkConditions: NetworkConditions | null
): Promise<void> {
return this.#frameManager
.networkManager()
.emulateNetworkConditions(networkConditions);
return this.#frameManager.networkManager.emulateNetworkConditions(
networkConditions
);
}
/**
@ -1220,12 +1227,10 @@ export class Page extends EventEmitter {
* the page and passes the result as the first argument to the `pageFunction`.
*
* @remarks
*
* If `pageFunction` returns a promise `$$eval` will wait for the promise to
* resolve and then return its value.
*
* @example
*
* ```ts
* // get the amount of divs on the page
* const divCount = await page.$$eval('div', divs => divs.length);
@ -1242,7 +1247,6 @@ export class Page extends EventEmitter {
* specific sub-type:
*
* @example
*
* ```ts
* // if you don't provide HTMLInputElement here, TS will error
* // as `value` is not on `Element`
@ -1256,7 +1260,6 @@ export class Page extends EventEmitter {
* type to tell the compiler what return type you expect from `$$eval`:
*
* @example
*
* ```ts
* // The compiler can infer the return type in this case, but if it can't
* // or if you want to be more explicit, provide it as the generic type.
@ -1268,9 +1271,9 @@ export class Page extends EventEmitter {
* @param selector - the
* {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
* to query for
* @param pageFunction - the function to be evaluated in the page context. Will
* be passed the result of `Array.from(document.querySelectorAll(selector))`
* as its first argument.
* @param pageFunction - the function to be evaluated in the page context.
* Will be passed the result of
* `Array.from(document.querySelectorAll(selector))` as its first argument.
* @param args - any additional arguments to pass through to `pageFunction`.
*
* @returns The result of calling `pageFunction`. If it returns an element it
@ -1295,8 +1298,10 @@ export class Page extends EventEmitter {
* The method evaluates the XPath expression relative to the page document as
* its context node. If there are no such elements, the method resolves to an
* empty array.
*
* @remarks
* Shortcut for {@link Frame.$x | Page.mainFrame().$x(expression) }.
*
* @param expression - Expression to evaluate
*/
async $x(expression: string): Promise<Array<ElementHandle<Node>>> {
@ -1371,10 +1376,13 @@ export class Page extends EventEmitter {
/**
* Adds a `<script>` tag into the page with the desired URL or content.
*
* @remarks
* Shortcut for {@link Frame.addScriptTag | page.mainFrame().addScriptTag(options) }.
* @returns Promise which resolves to the added tag when the script's onload fires or
* when the script content was injected into frame.
* Shortcut for
* {@link Frame.addScriptTag | page.mainFrame().addScriptTag(options)}.
*
* @returns Promise which resolves to the added tag when the script's onload
* fires or when the script content was injected into frame.
*/
async addScriptTag(options: {
url?: string;
@ -1401,16 +1409,19 @@ export class Page extends EventEmitter {
}
/**
* The method adds a function called `name` on the page's `window` object. When
* called, the function executes `puppeteerFunction` in node.js and returns a
* `Promise` which resolves to the return value of `puppeteerFunction`.
* The method adds a function called `name` on the page's `window` object.
* When called, the function executes `puppeteerFunction` in node.js and
* returns a `Promise` which resolves to the return value of
* `puppeteerFunction`.
*
* If the puppeteerFunction returns a `Promise`, it will be awaited.
*
* NOTE: Functions installed via `page.exposeFunction` survive navigations.
* @param name - Name of the function on the window object
* @param pptrFunction - Callback function which will be called in
* Puppeteer's context.
* :::note
*
* Functions installed via `page.exposeFunction` survive navigations.
*
* :::note
*
* @example
* An example of adding an `md5` function into the page:
* ```ts
@ -1433,6 +1444,8 @@ export class Page extends EventEmitter {
* await browser.close();
* })();
* ```
*
* @example
* An example of adding a `window.readfile` function into the page:
* ```ts
* const puppeteer = require('puppeteer');
@ -1458,6 +1471,10 @@ export class Page extends EventEmitter {
* await browser.close();
* })();
* ```
*
* @param name - Name of the function on the window object
* @param pptrFunction - Callback function which will be called in Puppeteer's
* context.
*/
async exposeFunction(
name: string,
@ -1495,24 +1512,36 @@ export class Page extends EventEmitter {
/**
* Provide credentials for `HTTP authentication`.
* @remarks To disable authentication, pass `null`.
*
* @remarks
* To disable authentication, pass `null`.
*/
async authenticate(credentials: Credentials): Promise<void> {
return this.#frameManager.networkManager().authenticate(credentials);
return this.#frameManager.networkManager.authenticate(credentials);
}
/**
* The extra HTTP headers will be sent with every request the page initiates.
* NOTE: All HTTP header names are lowercased. (HTTP headers are
*
* :::tip
*
* All HTTP header names are lowercased. (HTTP headers are
* case-insensitive, so this shouldnt impact your server code.)
* NOTE: page.setExtraHTTPHeaders does not guarantee the order of headers in
*
* :::
*
* :::note
*
* page.setExtraHTTPHeaders does not guarantee the order of headers in
* the outgoing requests.
*
* :::
*
* @param headers - An object containing additional HTTP headers to be sent
* with every request. All header values must be strings.
* @returns
*/
async setExtraHTTPHeaders(headers: Record<string, string>): Promise<void> {
return this.#frameManager.networkManager().setExtraHTTPHeaders(headers);
return this.#frameManager.networkManager.setExtraHTTPHeaders(headers);
}
/**
@ -1525,9 +1554,10 @@ export class Page extends EventEmitter {
userAgent: string,
userAgentMetadata?: Protocol.Emulation.UserAgentMetadata
): Promise<void> {
return this.#frameManager
.networkManager()
.setUserAgent(userAgent, userAgentMetadata);
return this.#frameManager.networkManager.setUserAgent(
userAgent,
userAgentMetadata
);
}
/**
@ -1560,8 +1590,9 @@ export class Page extends EventEmitter {
* - `JSHeapUsedSize` : Used JavaScript heap size.
*
* - `JSHeapTotalSize` : Total JavaScript heap size.
*
* @remarks
* NOTE: All timestamps are in monotonic time: monotonically increasing time
* All timestamps are in monotonic time: monotonically increasing time
* in seconds since an arbitrary point in the past.
*/
async metrics(): Promise<Metrics> {
@ -1954,7 +1985,7 @@ export class Page extends EventEmitter {
): Promise<HTTPRequest> {
const {timeout = this.#timeoutSettings.timeout()} = options;
return waitForEvent(
this.#frameManager.networkManager(),
this.#frameManager.networkManager,
NetworkManagerEmittedEvents.Request,
request => {
if (isString(urlOrPredicate)) {
@ -2003,7 +2034,7 @@ export class Page extends EventEmitter {
): Promise<HTTPResponse> {
const {timeout = this.#timeoutSettings.timeout()} = options;
return waitForEvent(
this.#frameManager.networkManager(),
this.#frameManager.networkManager,
NetworkManagerEmittedEvents.Response,
async response => {
if (isString(urlOrPredicate)) {
@ -2028,7 +2059,7 @@ export class Page extends EventEmitter {
): Promise<void> {
const {idleTime = 500, timeout = this.#timeoutSettings.timeout()} = options;
const networkManager = this.#frameManager.networkManager();
const networkManager = this.#frameManager.networkManager;
let idleResolveCallback: () => void;
const idlePromise = new Promise<void>(resolve => {
@ -2604,8 +2635,6 @@ export class Page extends EventEmitter {
}
/**
* @remarks
*
* Evaluates a function in the page's context and returns the result.
*
* If the function passed to `page.evaluteHandle` returns a Promise, the
@ -2708,7 +2737,7 @@ export class Page extends EventEmitter {
* @param enabled - sets the `enabled` state of cache
*/
async setCacheEnabled(enabled = true): Promise<void> {
await this.#frameManager.networkManager().setCacheEnabled(enabled);
await this.#frameManager.networkManager.setCacheEnabled(enabled);
}
/**

View File

@ -24,11 +24,11 @@ import {JSHandle} from './JSHandle.js';
*/
export interface CustomQueryHandler {
/**
* @returns A {@link Node} matching the given {@link selector} from {@link node}.
* @returns A {@link Node} matching the given `selector` from {@link node}.
*/
queryOne?: (node: Node, selector: string) => Node | null;
/**
* @returns Some {@link Node}s matching the given {@link selector} from {@link node}.
* @returns Some {@link Node}s matching the given `selector` from {@link node}.
*/
queryAll?: (node: Node, selector: string) => Node[];
}
@ -65,6 +65,7 @@ export interface InternalQueryHandler {
element: ElementHandle<Node>,
selector: string
) => Promise<JSHandle<Node[]>>;
/**
* Waits until a single node appears for a given selector and
* {@link ElementHandle}.
@ -95,11 +96,11 @@ function internalizeCustomQueryHandler(
return null;
};
internalHandler.waitFor = (
isolatedWorld: IsolatedWorld,
domWorld: IsolatedWorld,
selector: string,
options: WaitForSelectorOptions
) => {
return isolatedWorld._waitForSelectorInPage(queryOne, selector, options);
return domWorld._waitForSelectorInPage(queryOne, selector, options);
};
}

View File

@ -37,10 +37,11 @@ export type ConsoleAPICalledCallback = (
export type ExceptionThrownCallback = (
details: Protocol.Runtime.ExceptionDetails
) => void;
type JSHandleFactory = (obj: Protocol.Runtime.RemoteObject) => JSHandle;
/**
* The WebWorker class represents a
* This class represents a
* {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API | WebWorker}.
*
* @remarks
@ -67,7 +68,6 @@ export class WebWorker extends EventEmitter {
#executionContextCallback!: (value: ExecutionContext) => void;
/**
*
* @internal
*/
constructor(

View File

@ -553,7 +553,7 @@ export function createDeferredPromiseWithTimer<T>(
rejector = reject;
});
const timeoutId = setTimeout(() => {
rejector(new Error(timeoutMessage));
rejector(new TimeoutError(timeoutMessage));
}, timeout);
return Object.assign(taskPromise, {
resolved: () => {