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. | | [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. | | [Touchscreen](./puppeteer.touchscreen.md) | The Touchscreen class exposes touchscreen events. |
| [Tracing](./puppeteer.tracing.md) | The Tracing class exposes the tracing audit interface. | | [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 ## Enumerations

View File

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

View File

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

View File

@ -4,9 +4,9 @@ sidebar_label: ElementHandle.$$eval
# ElementHandle.$$eval() method # 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:** **Signature:**
@ -29,16 +29,20 @@ class ElementHandle {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| ------------ | -------------- | ----------- | | ------------ | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | | | selector | Selector | The selector to query for. |
| pageFunction | Func \| string | | | 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 | | | args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:** **Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt; Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
## Example 1 A promise to the result of the function.
## Example
HTML:
```html ```html
<div class="feed"> <div class="feed">
@ -47,9 +51,9 @@ Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
</div> </div>
``` ```
## Example 2 JavaScript:
```ts ```js
const feedHandle = await page.$('.feed'); const feedHandle = await page.$('.feed');
expect( expect(
await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)) await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))

View File

@ -4,9 +4,9 @@ sidebar_label: ElementHandle.$eval
# ElementHandle.$eval() method # 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:** **Signature:**
@ -29,15 +29,17 @@ class ElementHandle {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| ------------ | -------------- | ----------- | | ------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | | | selector | Selector | The selector to query for. |
| pageFunction | Func \| string | | | 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 | | | args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:** **Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt; Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
A promise to the result of the function.
## Example ## Example
```ts ```ts

View File

@ -42,11 +42,11 @@ The constructor for this class is marked as internal. Third-party code should no
## Methods ## Methods
| Method | Modifiers | Description | | Method | Modifiers | Description |
| -------------------------------------------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -------------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [$(selector)](./puppeteer.elementhandle._.md) | | Runs <code>element.querySelector</code> within the page. | | [$(selector)](./puppeteer.elementhandle._.md) | | Queries the current element for an element matching the given selector. |
| [$$(selector)](./puppeteer.elementhandle.__.md) | | Runs <code>element.querySelectorAll</code> within the page. | | [$$(selector)](./puppeteer.elementhandle.__.md) | | Queries the current element for all elements matching the given selector. |
| [$$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>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>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> | | [$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) | | | | [$x(expression)](./puppeteer.elementhandle._x.md) | | |
| [asElement()](./puppeteer.elementhandle.aselement.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. | | [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. |
@ -68,5 +68,5 @@ The constructor for this class is marked as internal. Third-party code should no
| [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. | | [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> | | [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). | | [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> | | [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) | | | | [waitForXPath(xpath, options)](./puppeteer.elementhandle.waitforxpath.md) | | |

View File

@ -4,9 +4,9 @@ sidebar_label: ElementHandle.waitForSelector
# ElementHandle.waitForSelector() method # 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:** **Signature:**
@ -22,22 +22,41 @@ class ElementHandle {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | --------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| selector | Selector | A [selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors) of an element to wait for | | selector | Selector | The selector to query and wait for. |
| options | Exclude&lt;[WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md), 'root'&gt; | <i>(Optional)</i> Optional waiting parameters | | options | Exclude&lt;[WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md), 'root'&gt; | <i>(Optional)</i> Options for customizing waiting behavior. |
**Returns:** **Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt; \| null&gt; 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 ## 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. 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 ## Example
An example of using `FileChooser`:
```ts ```ts
const [fileChooser] = await Promise.all([ const [fileChooser] = await Promise.all([
page.waitForFileChooser(), page.waitForFileChooser(),
@ -30,8 +30,6 @@ const [fileChooser] = await Promise.all([
await fileChooser.accept(['/tmp/myfile.pdf']); 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 ## Methods
| Method | Modifiers | Description | | Method | Modifiers | Description |

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.$
# Frame.$() method # Frame.$() method
This method queries the frame for the given selector. Queries the frame for an element matching the given selector.
**Signature:** **Signature:**
@ -19,11 +19,11 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | -------- | ------------------------ | | --------- | -------- | -------------------------- |
| selector | Selector | a selector to query for. | | selector | Selector | The selector to query for. |
**Returns:** **Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt; \| null&gt; 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 # Frame.$$() method
This runs `document.querySelectorAll` in the frame and returns the result. Queries the frame for all elements matching the given selector.
**Signature:** **Signature:**
@ -19,11 +19,11 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | -------- | ------------------------ | | --------- | -------- | -------------------------- |
| selector | Selector | a selector to search for | | selector | Selector | The selector to query for. |
**Returns:** **Returns:**
Promise&lt;Array&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt;&gt;&gt; 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 # 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:** **Signature:**
```typescript ```typescript
@ -25,23 +29,19 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| ------------ | -------------- | --------------------------------------------------------- | | ------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | the selector to query for | | selector | Selector | The selector to query for. |
| pageFunction | Func \| string | the function to be evaluated in the frame's context | | 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> | | args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:** **Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt; Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
## Remarks A promise to the result of the function.
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.
## Example ## Example
```ts ```js
const divsCounts = await frame.$$eval('div', divs => divs.length); const divsCounts = await frame.$$eval('div', divs => divs.length);
``` ```

View File

@ -4,6 +4,10 @@ sidebar_label: Frame.$eval
# Frame.$eval() method # 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:** **Signature:**
```typescript ```typescript
@ -25,20 +29,16 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| ------------ | -------------- | --------------------------------------------------------- | | ------------ | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | Selector | the selector to query for | | selector | Selector | The selector to query for. |
| pageFunction | Func \| string | the function to be evaluated in the frame's context | | 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> | | args | Params | Additional arguments to pass to <code>pageFunction</code>. |
**Returns:** **Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt; Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
## Remarks A promise to the result of the function.
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.
## Example ## Example

View File

@ -4,7 +4,11 @@ sidebar_label: Frame.$x
# Frame.$x() method # 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:** **Signature:**

View File

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

View File

@ -10,18 +10,20 @@ Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<s
```typescript ```typescript
class Frame { class Frame {
addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle<Node>>; addStyleTag(
options: FrameAddStyleTagOptions
): Promise<ElementHandle<HTMLStyleElement | HTMLLinkElement>>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ----------------------------------------------------------------- | ------------------------------------- | | --------- | ----------------------------------------------------------------- | --------------------------- |
| options | [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) | configure the CSS to add to the page. | | options | [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) | Options for the style link. |
**Returns:** **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. 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 # Frame.click() method
This method clicks the first element found that matches `selector`. Clicks the first element found that matches `selector`.
**Signature:** **Signature:**
@ -24,8 +24,8 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | --------- | -------------------------------------------------------------------------------------------- | -------------------------- |
| selector | string | the selector to search for to click. If there are multiple elements, the first will be clicked. | | selector | string | The selector to query for. |
| options | { delay?: number; button?: [MouseButton](./puppeteer.mousebutton.md); clickCount?: number; } | <i>(Optional)</i> | | options | { delay?: number; button?: [MouseButton](./puppeteer.mousebutton.md); clickCount?: number; } | <i>(Optional)</i> |
**Returns:** **Returns:**
@ -34,11 +34,9 @@ Promise&lt;void&gt;
## Remarks ## 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: ```ts
```javascript
const [response] = await Promise.all([ const [response] = await Promise.all([
page.waitForNavigation(waitOptions), page.waitForNavigation(waitOptions),
frame.click(selector, clickOptions), frame.click(selector, clickOptions),

View File

@ -16,4 +16,4 @@ class Frame {
Promise&lt;string&gt; 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 # Frame.evaluate() method
Behaves identically to [Page.evaluate()](./puppeteer.page.evaluate.md) except it's run within the the context of this frame.
**Signature:** **Signature:**
```typescript ```typescript
@ -28,7 +30,3 @@ class Frame {
**Returns:** **Returns:**
Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt; 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 # Frame.evaluateHandle() method
Behaves identically to [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md) except it's run within the context of this frame.
**Signature:** **Signature:**
```typescript ```typescript
@ -28,9 +30,3 @@ class Frame {
**Returns:** **Returns:**
Promise&lt;[HandleFor](./puppeteer.handlefor.md)&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;&gt; 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 # Frame.focus() method
This method fetches an element with `selector` and focuses it. Focuses the first element that matches the `selector`.
**Signature:** **Signature:**
@ -17,13 +17,13 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------ | ------------------------------------------------------------------------------------------------- | | --------- | ------ | -------------------------- |
| selector | string | the selector for the element to focus. If there are multiple elements, the first will be focused. | | selector | string | The selector to query for. |
**Returns:** **Returns:**
Promise&lt;void&gt; 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 # Frame.goto() method
Navigates a frame to the given url.
**Signature:** **Signature:**
```typescript ```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. 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 ## 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 # 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:** **Signature:**
@ -17,13 +17,13 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------ | ------------------------------------------------------------------------------------------------- | | --------- | ------ | -------------------------- |
| selector | string | the selector for the element to hover. If there are multiple elements, the first will be hovered. | | selector | string | The selector to query for. |
**Returns:** **Returns:**
Promise&lt;void&gt; 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 boolean
`true` if the frame is an OOP frame, or `false` otherwise. `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: `Frame` object lifecycles are controlled by three events that are all dispatched on the page object:
- [PageEmittedEvents.FrameAttached](./puppeteer.pageemittedevents.md) - [PageEmittedEvents.FrameAttached](./puppeteer.pageemittedevents.md) - [PageEmittedEvents.FrameNavigated](./puppeteer.pageemittedevents.md) - [PageEmittedEvents.FrameDetached](./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. 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.
@ -60,36 +56,36 @@ console.log(text);
## Methods ## Methods
| Method | Modifiers | Description | | Method | Modifiers | Description |
| ------------------------------------------------------------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------------------------------------------------------------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [$(selector)](./puppeteer.frame._.md) | | This method queries the frame for the given selector. | | [$(selector)](./puppeteer.frame._.md) | | Queries the frame for an element matching the given selector. |
| [$$(selector)](./puppeteer.frame.__.md) | | This runs <code>document.querySelectorAll</code> in the frame and returns the result. | | [$$(selector)](./puppeteer.frame.__.md) | | Queries the frame for all elements matching the given selector. |
| [$$eval(selector, pageFunction, args)](./puppeteer.frame.__eval.md) | | | | [$$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) | | | | [$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) | | This method evaluates the given XPath expression and returns the results. | | [$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. | | [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. | | [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) | | | | [childFrames()](./puppeteer.frame.childframes.md) | | |
| [click(selector, options)](./puppeteer.frame.click.md) | | This method clicks the first element found that matches <code>selector</code>. | | [click(selector, options)](./puppeteer.frame.click.md) | | Clicks the first element found that matches <code>selector</code>. |
| [content()](./puppeteer.frame.content.md) | | | | [content()](./puppeteer.frame.content.md) | | |
| [evaluate(pageFunction, args)](./puppeteer.frame.evaluate.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) | | | | [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) | | | | [executionContext()](./puppeteer.frame.executioncontext.md) | | |
| [focus(selector)](./puppeteer.frame.focus.md) | | This method fetches an element with <code>selector</code> and focuses it. | | [focus(selector)](./puppeteer.frame.focus.md) | | Focuses the first element that matches the <code>selector</code>. |
| [goto(url, options)](./puppeteer.frame.goto.md) | | | | [goto(url, options)](./puppeteer.frame.goto.md) | | Navigates a frame to the given url. |
| [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. | | [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) | | | | [isDetached()](./puppeteer.frame.isdetached.md) | | |
| [isOOPFrame()](./puppeteer.frame.isoopframe.md) | | | | [isOOPFrame()](./puppeteer.frame.isoopframe.md) | | |
| [name()](./puppeteer.frame.name.md) | | | | [name()](./puppeteer.frame.name.md) | | |
| [page()](./puppeteer.frame.page.md) | | | | [page()](./puppeteer.frame.page.md) | | |
| [parentFrame()](./puppeteer.frame.parentframe.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. | | [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. | | [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. | | [tap(selector)](./puppeteer.frame.tap.md) | | Taps the first element that matches the <code>selector</code>. |
| [title()](./puppeteer.frame.title.md) | | | | [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. | | [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) | | | | [url()](./puppeteer.frame.url.md) | | |
| [waitForFunction(pageFunction, options, args)](./puppeteer.frame.waitforfunction.md) | | | | [waitForFunction(pageFunction, options, args)](./puppeteer.frame.waitforfunction.md) | | |
| [waitForNavigation(options)](./puppeteer.frame.waitfornavigation.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) | | | | [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. | | [waitForTimeout(milliseconds)](./puppeteer.frame.waitfortimeout.md) | | Causes your script to wait for the given number of milliseconds. |
| [waitForXPath(xpath, options)](./puppeteer.frame.waitforxpath.md) | | | | [waitForXPath(xpath, options)](./puppeteer.frame.waitforxpath.md) | | |

View File

@ -16,10 +16,8 @@ class Frame {
string string
the frame's `name` attribute as specified in the tag. The frame's `name` attribute as specified in the tag.
## Remarks ## Remarks
If the name is empty, it returns the `id` attribute instead. This value is calculated once when the frame is created, and will not update if the attribute is changed later.
Note: 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) [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 # 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:** **Signature:**
@ -17,9 +17,9 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| selector | string | a selector to query the frame for | | selector | string | The selector to query 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. | | 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:** **Returns:**
@ -27,9 +27,9 @@ Promise&lt;string\[\]&gt;
the list of values that were successfully selected. 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 ## Example

View File

@ -25,7 +25,7 @@ class Frame {
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| html | string | HTML markup to assign to the page. | | 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:** **Returns:**

View File

@ -4,7 +4,7 @@ sidebar_label: Frame.tap
# Frame.tap() method # 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:** **Signature:**
@ -17,15 +17,13 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------ | -------------------- | | --------- | ------ | -------------------------- |
| selector | string | the selector to tap. | | selector | string | The selector to query for. |
**Returns:** **Returns:**
Promise&lt;void&gt; Promise&lt;void&gt;
a promise that resolves when the element has been tapped. ## Exceptions
## Remarks Throws if there's no element matching `selector`.
If there's no element matching `selector`, the method throws an error.

View File

@ -32,8 +32,6 @@ class Frame {
Promise&lt;void&gt; Promise&lt;void&gt;
a promise that resolves when the typing is complete.
## Remarks ## Remarks
To press a special key, like `Control` or `ArrowDown`, use [Keyboard.press()](./puppeteer.keyboard.press.md). 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. the promise which resolve when the `pageFunction` returns a truthy value.
## Remarks
## Example ## Example
The `waitForFunction` can be used to observe viewport size change: The `waitForFunction` can be used to observe viewport size change:

View File

@ -4,6 +4,10 @@ sidebar_label: Frame.waitForNavigation
# Frame.waitForNavigation() method # 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:** **Signature:**
```typescript ```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. a promise that resolves when the frame navigates to a new URL.
## Remarks ## Example
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:
```ts ```ts
const [response] = await Promise.all([ const [response] = await Promise.all([
@ -39,5 +41,3 @@ const [response] = await Promise.all([
frame.click('a.my-link'), 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 # Frame.waitForSelector() method
Wait for an element matching the given selector to appear in the frame.
This method works across navigations.
**Signature:** **Signature:**
```typescript ```typescript
@ -18,21 +22,19 @@ class Frame {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | --------- | --------------------------------------------------------------- | ----------------------------------------------------------- |
| selector | Selector | the selector to wait for. | | selector | Selector | The selector to query and 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. | | options | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | <i>(Optional)</i> Options for customizing waiting behavior. |
**Returns:** **Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;[NodeFor](./puppeteer.nodefor.md)&lt;Selector&gt;&gt; \| null&gt; 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. Throws if an element matching the given selector doesn't appear.
This method works across navigations.
## Example ## Example

View File

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

View File

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

View File

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

View File

@ -13,7 +13,7 @@ export interface GeolocationOptions
## Properties ## Properties
| Property | Modifiers | Type | Description | | Property | Modifiers | Type | Description |
| -------------------------------------------------------- | --------- | ------ | ------------------------------------------------------- | | -------------------------------------------------------- | --------- | ------ | --------------------------------------------------------- |
| [accuracy?](./puppeteer.geolocationoptions.accuracy.md) | | number | <i>(Optional)</i> Optional non-negative accuracy value. | | [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. | | [latitude](./puppeteer.geolocationoptions.latitude.md) | | number | Longitude between <code>-180</code> and <code>180</code>. |
| [longitude](./puppeteer.geolocationoptions.longitude.md) | | number | Latitude between -90 and 90. | | [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 # 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:** **Signature:**
```typescript ```typescript
@ -31,12 +35,6 @@ Promise&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;
the return value of `pageFunction`. 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 ## Example 1
```ts ```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. 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:** **Signature:**
@ -36,7 +40,7 @@ class Page {
Promise&lt;void&gt; Promise&lt;void&gt;
## Example ## Example 1
An example of adding an `md5` function into the page: 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: An example of adding a `window.readfile` function into the page:
```ts ```ts

View File

@ -75,7 +75,7 @@ page.off('request', logRequest);
## Methods ## Methods
| Method | Modifiers | Description | | 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) | | 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>. | | [$$(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>Array.from(document.querySelectorAll(selector))</code> within the page and passes the result as the first argument to the <code>pageFunction</code>. |
@ -101,10 +101,10 @@ page.off('request', logRequest);
| [emulateNetworkConditions(networkConditions)](./puppeteer.page.emulatenetworkconditions.md) | | | | [emulateNetworkConditions(networkConditions)](./puppeteer.page.emulatenetworkconditions.md) | | |
| [emulateTimezone(timezoneId)](./puppeteer.page.emulatetimezone.md) | | | | [emulateTimezone(timezoneId)](./puppeteer.page.emulatetimezone.md) | | |
| [emulateVisionDeficiency(type)](./puppeteer.page.emulatevisiondeficiency.md) | | Simulates the given vision deficiency on the page. | | [emulateVisionDeficiency(type)](./puppeteer.page.emulatevisiondeficiency.md) | | Simulates the given vision deficiency on the page. |
| [evaluate(pageFunction, args)](./puppeteer.page.evaluate.md) | | | | [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) | | | | [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> | | [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> | | [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. | | [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) | | | | [frames()](./puppeteer.page.frames.md) | | |
| [goBack(options)](./puppeteer.page.goback.md) | | This method navigate to the previous page in history. | | [goBack(options)](./puppeteer.page.goback.md) | | This method navigate to the previous page in history. |
@ -131,11 +131,11 @@ page.off('request', logRequest);
| [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> | | [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) | | | | [setDefaultTimeout(timeout)](./puppeteer.page.setdefaulttimeout.md) | | |
| [setDragInterception(enabled)](./puppeteer.page.setdraginterception.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. | | [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. | | [setGeolocation(options)](./puppeteer.page.setgeolocation.md) | | Sets the page's geolocation. |
| [setJavaScriptEnabled(enabled)](./puppeteer.page.setjavascriptenabled.md) | | | | [setJavaScriptEnabled(enabled)](./puppeteer.page.setjavascriptenabled.md) | | |
| [setOfflineMode(enabled)](./puppeteer.page.setofflinemode.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> | | [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) | | | | [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> | | [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. | | [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. |

View File

@ -46,4 +46,4 @@ Object containing metrics as key/value pairs.
## Remarks ## 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 # 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:** **Signature:**

View File

@ -26,7 +26,7 @@ Promise&lt;void&gt;
## Remarks ## 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 ## 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. 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. 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 ## 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 # ScreenshotOptions.fullPage property
When true, takes a screenshot of the full page. When `true`, takes a screenshot of the full page.
**Signature:** **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. | | [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. | | [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. | | [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. | | [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. | | [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. | | [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

@ -13,6 +13,6 @@ export interface WaitForOptions
## Properties ## Properties
| Property | Modifiers | Type | Description | | 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. | | [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> | | [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 # 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:** **Signature:**
@ -13,7 +15,3 @@ interface WaitForOptions {
timeout?: number; 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 # 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:** **Signature:**
```typescript ```typescript

View File

@ -13,8 +13,8 @@ export interface WaitForSelectorOptions
## Properties ## Properties
| Property | Modifiers | Type | Description | | Property | Modifiers | Type | Description |
| --------------------------------------------------------- | --------- | --------------------------------------------------------- | ----------------- | | --------------------------------------------------------- | --------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [hidden?](./puppeteer.waitforselectoroptions.hidden.md) | | boolean | <i>(Optional)</i> | | [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> | | [root?](./puppeteer.waitforselectoroptions.root.md) | | [ElementHandle](./puppeteer.elementhandle.md)&lt;Node&gt; | <i>(Optional)</i> |
| [timeout?](./puppeteer.waitforselectoroptions.timeout.md) | | number | <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> | | [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 # 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:** **Signature:**
```typescript ```typescript

View File

@ -4,6 +4,8 @@ sidebar_label: WaitForSelectorOptions.visible
# WaitForSelectorOptions.visible property # 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:** **Signature:**
```typescript ```typescript

View File

@ -13,5 +13,5 @@ export interface WaitTimeoutOptions
## Properties ## Properties
| Property | Modifiers | Type | Description | | 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. | | [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 # 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:** **Signature:**
@ -13,7 +15,3 @@ interface WaitTimeoutOptions {
timeout?: number; 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 # 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:** **Signature:**

View File

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

View File

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

View File

@ -1,9 +1,13 @@
import {Protocol} from 'devtools-protocol'; import {Protocol} from 'devtools-protocol';
import {assert} from './assert.js'; import {assert} from './assert.js';
import {CDPSession} from './Connection.js'; import {CDPSession} from './Connection.js';
import {WaitForSelectorOptions} from './IsolatedWorld.js';
import {ExecutionContext} from './ExecutionContext.js'; import {ExecutionContext} from './ExecutionContext.js';
import {Frame, FrameManager} from './FrameManager.js'; import {Frame, FrameManager} from './FrameManager.js';
import {
MAIN_WORLD,
PUPPETEER_WORLD,
WaitForSelectorOptions,
} from './IsolatedWorld.js';
import { import {
BoundingBox, BoundingBox,
BoxModel, BoxModel,
@ -88,34 +92,186 @@ export class ElementHandle<
} }
/** /**
* Wait for the `selector` to appear within the element. If at the moment of calling the * Queries the current element for an element matching the given selector.
* 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 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 * @param selector - The selector to query for.
* {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector} * @returns An array of {@link ElementHandle | element handles} that point to
* of an element to wait for * elements matching the given selector.
* @param options - Optional waiting parameters */
* @returns Promise which resolves when element specified by selector string async $$<Selector extends string>(
* is added to DOM. Resolves to `null` if waiting for hidden: `true` and selector: Selector
* selector is not found in DOM. ): Promise<Array<ElementHandle<NodeFor<Selector>>>> {
* @remarks const {updatedSelector, queryHandler} =
* The optional parameters in `options` are: 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 * If the given function returns a promise, then this method will wait till
* visible, i.e. to not have `display: none` or `visibility: hidden` CSS * the promise resolves.
* properties. Defaults to `false`.
* *
* - `hidden`: wait for the selected element to not be found in the DOM or to be hidden, * @example
* i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to * ```ts
* `false`. * 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` * @param selector - The selector to query for.
* (30 seconds). Pass `0` to disable timeout. The default value can be changed * @param pageFunction - The function to be evaluated in this element's page's
* by using the {@link Page.setDefaultTimeout} method. * 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>( async waitForSelector<Selector extends string>(
selector: Selector, selector: Selector,
@ -123,16 +279,19 @@ export class ElementHandle<
): Promise<ElementHandle<NodeFor<Selector>> | null> { ): Promise<ElementHandle<NodeFor<Selector>> | null> {
const frame = this._context.frame(); const frame = this._context.frame();
assert(frame); assert(frame);
const adoptedRoot = await frame._secondaryWorld.adoptHandle(this); const adoptedRoot = await frame.worlds[PUPPETEER_WORLD].adoptHandle(this);
const handle = await frame._secondaryWorld.waitForSelector(selector, { const handle = await frame.worlds[PUPPETEER_WORLD].waitForSelector(
selector,
{
...options, ...options,
root: adoptedRoot, root: adoptedRoot,
}); }
);
await adoptedRoot.dispose(); await adoptedRoot.dispose();
if (!handle) { if (!handle) {
return null; return null;
} }
const result = (await frame._mainWorld.adoptHandle( const result = (await frame.worlds[MAIN_WORLD].adoptHandle(
handle handle
)) as ElementHandle<NodeFor<Selector>>; )) as ElementHandle<NodeFor<Selector>>;
await handle.dispose(); 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 * 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 * method the `xpath` already exists, the method will return immediately. If
* the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the * the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the
* function will throw. * 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 * This method works across navigation
* ```ts * ```ts
@ -188,8 +349,9 @@ export class ElementHandle<
* Defaults to `false`. * Defaults to `false`.
* *
* - `timeout`: A number which is maximum time to wait for in milliseconds. * - `timeout`: A number which is maximum time to wait for in milliseconds.
* Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default * Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
* value can be changed by using the {@link Page.setDefaultTimeout} method. * default value can be changed by using the {@link Page.setDefaultTimeout}
* method.
*/ */
async waitForXPath( async waitForXPath(
xpath: string, xpath: string,
@ -818,150 +980,6 @@ export class ElementHandle<
return imageData; 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. * 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. * File choosers let you react to the page requesting for a file.
*
* @remarks * @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 * @example
* An example of using `FileChooser`:
* ```ts * ```ts
* const [fileChooser] = await Promise.all([ * const [fileChooser] = await Promise.all([
* page.waitForFileChooser(), * page.waitForFileChooser(),
@ -31,9 +36,7 @@ import {ElementHandle} from './ElementHandle.js';
* ]); * ]);
* await fileChooser.accept(['/tmp/myfile.pdf']); * 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 * @public
*/ */
export class FileChooser { 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 { isMultiple(): boolean {
return this.#multiple; return this.#multiple;
@ -61,8 +66,10 @@ export class FileChooser {
/** /**
* Accept the file chooser request with given paths. * 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> { async accept(filePaths: string[]): Promise<void> {
assert( assert(

File diff suppressed because it is too large Load Diff

View File

@ -55,8 +55,27 @@ declare const checkWaitForOptions: (
* @public * @public
*/ */
export interface WaitForSelectorOptions { 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; 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; 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; timeout?: number;
root?: ElementHandle<Node>; root?: ElementHandle<Node>;
} }
@ -69,6 +88,29 @@ export interface PageBinding {
pptrFunction: Function; 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 * @internal
*/ */
@ -187,19 +229,18 @@ export class IsolatedWorld {
async $<Selector extends string>( async $<Selector extends string>(
selector: Selector selector: Selector
): Promise<ElementHandle<NodeFor<Selector>> | null> { ): Promise<ElementHandle<NodeFor<Selector>> | null> {
const document = await this._document(); const document = await this.document();
const value = await document.$(selector); return document.$(selector);
return value;
} }
async $$<Selector extends string>( async $$<Selector extends string>(
selector: Selector selector: Selector
): Promise<Array<ElementHandle<NodeFor<Selector>>>> { ): Promise<Array<ElementHandle<NodeFor<Selector>>>> {
const document = await this._document(); const document = await this.document();
return document.$$(selector); return document.$$(selector);
} }
async _document(): Promise<ElementHandle<Document>> { async document(): Promise<ElementHandle<Document>> {
if (this.#documentPromise) { if (this.#documentPromise) {
return this.#documentPromise; return this.#documentPromise;
} }
@ -212,9 +253,8 @@ export class IsolatedWorld {
} }
async $x(expression: string): Promise<Array<ElementHandle<Node>>> { async $x(expression: string): Promise<Array<ElementHandle<Node>>> {
const document = await this._document(); const document = await this.document();
const value = await document.$x(expression); return document.$x(expression);
return value;
} }
async $eval< async $eval<
@ -228,7 +268,7 @@ export class IsolatedWorld {
pageFunction: Func | string, pageFunction: Func | string,
...args: Params ...args: Params
): Promise<Awaited<ReturnType<Func>>> { ): Promise<Awaited<ReturnType<Func>>> {
const document = await this._document(); const document = await this.document();
return document.$eval(selector, pageFunction, ...args); return document.$eval(selector, pageFunction, ...args);
} }
@ -243,9 +283,22 @@ export class IsolatedWorld {
pageFunction: Func | string, pageFunction: Func | string,
...args: Params ...args: Params
): Promise<Awaited<ReturnType<Func>>> { ): Promise<Awaited<ReturnType<Func>>> {
const document = await this._document(); const document = await this.document();
const value = await document.$$eval(selector, pageFunction, ...args); return document.$$eval(selector, pageFunction, ...args);
return value; }
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> { async content(): Promise<string> {
@ -299,7 +352,6 @@ export class IsolatedWorld {
* Adds a script tag into the current context. * Adds a script tag into the current context.
* *
* @remarks * @remarks
*
* You can pass a URL, filepath or string of contents. Note that when running Puppeteer * 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 * in a browser environment you cannot pass a filepath and should use either
* `url` or `content`. * `url` or `content`.
@ -399,27 +451,23 @@ export class IsolatedWorld {
* Adds a style tag into the current context. * Adds a style tag into the current context.
* *
* @remarks * @remarks
*
* You can pass a URL, filepath or string of contents. Note that when running Puppeteer * 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 * in a browser environment you cannot pass a filepath and should use either
* `url` or `content`. * `url` or `content`.
*
*/ */
async addStyleTag(options: { async addStyleTag(options: {
url?: string; url?: string;
path?: string; path?: string;
content?: string; content?: string;
}): Promise<ElementHandle<Node>> { }): Promise<ElementHandle<HTMLStyleElement | HTMLLinkElement>> {
const {url = null, path = null, content = null} = options; const {url = null, path = null, content = null} = options;
if (url !== null) { if (url !== null) {
try { try {
const context = await this.executionContext(); const context = await this.executionContext();
const handle = await context.evaluateHandle(addStyleUrl, url); return (await context.evaluateHandle(
const elementHandle = handle.asElement(); addStyleUrl,
if (elementHandle === null) { url
throw new Error('Style element is not found'); )) as ElementHandle<HTMLLinkElement>;
}
return elementHandle;
} catch (error) { } catch (error) {
throw new Error(`Loading style from ${url} failed`); throw new Error(`Loading style from ${url} failed`);
} }
@ -441,22 +489,18 @@ export class IsolatedWorld {
let contents = await fs.readFile(path, 'utf8'); let contents = await fs.readFile(path, 'utf8');
contents += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/'; contents += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/';
const context = await this.executionContext(); const context = await this.executionContext();
const handle = await context.evaluateHandle(addStyleContent, contents); return (await context.evaluateHandle(
const elementHandle = handle.asElement(); addStyleContent,
if (elementHandle === null) { contents
throw new Error('Style element is not found'); )) as ElementHandle<HTMLStyleElement>;
}
return elementHandle;
} }
if (content !== null) { if (content !== null) {
const context = await this.executionContext(); const context = await this.executionContext();
const handle = await context.evaluateHandle(addStyleContent, content); return (await context.evaluateHandle(
const elementHandle = handle.asElement(); addStyleContent,
if (elementHandle === null) { content
throw new Error('Style element is not found'); )) as ElementHandle<HTMLStyleElement>;
}
return elementHandle;
} }
throw new Error( throw new Error(
@ -539,20 +583,6 @@ export class IsolatedWorld {
await handle.dispose(); 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 // 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. // first one to set up the binding in the page before running the others.
#settingUpBinding: Promise<void> | null = null; #settingUpBinding: Promise<void> | null = null;

View File

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

View File

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

View File

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