chore(docs): document Frame class (#6188)

* chore: document Frame class
This commit is contained in:
Jack Franklin 2020-07-09 14:22:58 +01:00 committed by GitHub
parent b9667f9331
commit 24cb6a28ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
53 changed files with 1200 additions and 183 deletions

View File

@ -4,6 +4,8 @@
## Frame.$() method
This method queries the frame for the given selector.
<b>Signature:</b>
```typescript
@ -14,9 +16,11 @@ $(selector: string): Promise<ElementHandle | null>;
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| selector | string | a selector to query for. |
<b>Returns:</b>
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md) \| null&gt;
A promise which resolves to an `ElementHandle` pointing at the element, or `null` if it was not found.

View File

@ -4,6 +4,8 @@
## Frame.$$() method
This runs `document.querySelectorAll` in the frame and returns the result.
<b>Signature:</b>
```typescript
@ -14,9 +16,11 @@ $$(selector: string): Promise<ElementHandle[]>;
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| selector | string | a selector to search for |
<b>Returns:</b>
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)<!-- -->\[\]&gt;
An array of element handles pointing to the found frame elements.

View File

@ -14,11 +14,25 @@ $$eval<ReturnType>(selector: string, pageFunction: (elements: Element[], ...args
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| pageFunction | (elements: Element\[\], ...args: unknown\[\]) =&gt; ReturnType \| Promise&lt;ReturnType&gt; | |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | |
| selector | string | the selector to query for |
| pageFunction | (elements: Element\[\], ...args: unknown\[\]) =&gt; ReturnType \| Promise&lt;ReturnType&gt; | the function to be evaluated in the frame's context |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | additional arguments to pass to <code>pageFuncton</code> |
<b>Returns:</b>
Promise&lt;[WrapElementHandle](./puppeteer.wrapelementhandle.md)<!-- -->&lt;ReturnType&gt;&gt;
## Remarks
This method runs `Array.from(document.querySelectorAll(selector))` within the frame and passes it as the first argument to `pageFunction`<!-- -->.
If `pageFunction` returns a Promise, then `frame.$$eval` would wait for the promise to resolve and return its value.
## Example
```js
const divsCounts = await frame.$$eval('div', divs => divs.length);
```

View File

@ -1,15 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [Frame](./puppeteer.frame.md) &gt; [\_detach](./puppeteer.frame._detach.md)
## Frame.\_detach() method
<b>Signature:</b>
```typescript
_detach(): void;
```
<b>Returns:</b>
void

View File

@ -14,11 +14,25 @@ $eval<ReturnType>(selector: string, pageFunction: (element: Element, ...args: un
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| pageFunction | (element: Element, ...args: unknown\[\]) =&gt; ReturnType \| Promise&lt;ReturnType&gt; | |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | |
| selector | string | the selector to query for |
| pageFunction | (element: Element, ...args: unknown\[\]) =&gt; ReturnType \| Promise&lt;ReturnType&gt; | the function to be evaluated in the frame's context |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | additional arguments to pass to <code>pageFuncton</code> |
<b>Returns:</b>
Promise&lt;[WrapElementHandle](./puppeteer.wrapelementhandle.md)<!-- -->&lt;ReturnType&gt;&gt;
## Remarks
This method runs `document.querySelector` within the frame and passes it as the first argument to `pageFunction`<!-- -->.
If `pageFunction` returns a Promise, then `frame.$eval` would wait for the promise to resolve and return its value.
## Example
```js
const searchValue = await frame.$eval('#search', el => el.value);
```

View File

@ -1,22 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [Frame](./puppeteer.frame.md) &gt; [\_navigated](./puppeteer.frame._navigated.md)
## Frame.\_navigated() method
<b>Signature:</b>
```typescript
_navigated(framePayload: Protocol.Page.Frame): void;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| framePayload | Protocol.Page.Frame | |
<b>Returns:</b>
void

View File

@ -1,22 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [Frame](./puppeteer.frame.md) &gt; [\_navigatedWithinDocument](./puppeteer.frame._navigatedwithindocument.md)
## Frame.\_navigatedWithinDocument() method
<b>Signature:</b>
```typescript
_navigatedWithinDocument(url: string): void;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| url | string | |
<b>Returns:</b>
void

View File

@ -1,23 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [Frame](./puppeteer.frame.md) &gt; [\_onLifecycleEvent](./puppeteer.frame._onlifecycleevent.md)
## Frame.\_onLifecycleEvent() method
<b>Signature:</b>
```typescript
_onLifecycleEvent(loaderId: string, name: string): void;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| loaderId | string | |
| name | string | |
<b>Returns:</b>
void

View File

@ -1,15 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [Frame](./puppeteer.frame.md) &gt; [\_onLoadingStopped](./puppeteer.frame._onloadingstopped.md)
## Frame.\_onLoadingStopped() method
<b>Signature:</b>
```typescript
_onLoadingStopped(): void;
```
<b>Returns:</b>
void

View File

@ -4,6 +4,8 @@
## Frame.$x() method
This method evaluates the given XPath expression and returns the results.
<b>Signature:</b>
```typescript
@ -14,7 +16,7 @@ $x(expression: string): Promise<ElementHandle[]>;
| Parameter | Type | Description |
| --- | --- | --- |
| expression | string | |
| expression | string | the XPath expression to evaluate. |
<b>Returns:</b>

View File

@ -4,24 +4,23 @@
## Frame.addScriptTag() method
Adds a `<script>` tag into the page with the desired url or content.
<b>Signature:</b>
```typescript
addScriptTag(options: {
url?: string;
path?: string;
content?: string;
type?: string;
}): Promise<ElementHandle>;
addScriptTag(options: FrameAddScriptTagOptions): Promise<ElementHandle>;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| options | { url?: string; path?: string; content?: string; type?: string; } | |
| options | [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) | configure the script to add to the page. |
<b>Returns:</b>
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)<!-- -->&gt;
a promise that resolves to the added tag when the script's `onload` event fires or when the script content was injected into the frame.

View File

@ -4,23 +4,23 @@
## Frame.addStyleTag() method
Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
<b>Signature:</b>
```typescript
addStyleTag(options: {
url?: string;
path?: string;
content?: string;
}): Promise<ElementHandle>;
addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle>;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| options | { url?: string; path?: string; content?: string; } | |
| options | [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) | configure the CSS to add to the page. |
<b>Returns:</b>
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)<!-- -->&gt;
a promise that resolves to the added tag when the stylesheets's `onload` event fires or when the CSS content was injected into the frame.

View File

@ -13,3 +13,5 @@ childFrames(): Frame[];
[Frame](./puppeteer.frame.md)<!-- -->\[\]
an array of child frames.

View File

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

View File

@ -13,3 +13,5 @@ content(): Promise<string>;
Promise&lt;string&gt;
the full HTML contents of the frame, including the doctype.

View File

@ -14,10 +14,14 @@ evaluate<ReturnType extends any>(pageFunction: Function | string, ...args: unkno
| Parameter | Type | Description |
| --- | --- | --- |
| pageFunction | Function \| string | |
| args | unknown\[\] | |
| pageFunction | Function \| string | a function that is run within the frame |
| args | unknown\[\] | arguments to be passed to the pageFunction |
<b>Returns:</b>
Promise&lt;ReturnType&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

@ -14,10 +14,16 @@ evaluateHandle<HandlerType extends JSHandle = JSHandle>(pageFunction: EvaluateHa
| Parameter | Type | Description |
| --- | --- | --- |
| pageFunction | [EvaluateHandleFn](./puppeteer.evaluatehandlefn.md) | |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | |
| pageFunction | [EvaluateHandleFn](./puppeteer.evaluatehandlefn.md) | a function that is run within the frame |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | arguments to be passed to the pageFunction |
<b>Returns:</b>
Promise&lt;HandlerType&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

@ -13,3 +13,5 @@ executionContext(): Promise<ExecutionContext>;
Promise&lt;[ExecutionContext](./puppeteer.executioncontext.md)<!-- -->&gt;
a promise that resolves to the frame's default execution context.

View File

@ -4,6 +4,8 @@
## Frame.focus() method
This method fetches an element with `selector` and focuses it.
<b>Signature:</b>
```typescript
@ -14,9 +16,13 @@ focus(selector: string): Promise<void>;
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| selector | string | the selector for the element to focus. If there are multiple elements, the first will be focused. |
<b>Returns:</b>
Promise&lt;void&gt;
## Remarks
If there's no element matching `selector`<!-- -->, the method throws an error.

View File

@ -18,10 +18,30 @@ goto(url: string, options?: {
| Parameter | Type | Description |
| --- | --- | --- |
| url | string | |
| options | { referer?: string; timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)<!-- -->\[\]; } | |
| url | string | the URL to navigate the frame to. This should include the scheme, e.g. <code>https://</code>. |
| options | { referer?: string; timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)<!-- -->\[\]; } | navigation options. <code>waitUntil</code> is useful to define when the navigation should be considered successful - see the docs for [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) for more details. |
<b>Returns:</b>
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.
## Remarks
`frame.goto` 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.
`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,6 +4,8 @@
## 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.
<b>Signature:</b>
```typescript
@ -14,9 +16,13 @@ hover(selector: string): Promise<void>;
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| selector | string | the selector for the element to hover. If there are multiple elements, the first will be hovered. |
<b>Returns:</b>
Promise&lt;void&gt;
## Remarks
If there's no element matching `selector`<!-- -->, the method throws an

View File

@ -13,3 +13,5 @@ isDetached(): boolean;
boolean
`true` if the frame has been detached, or `false` otherwise.

View File

@ -4,6 +4,8 @@
## Frame class
At every point of time, page exposes its current frame tree via the [page.mainFrame](./puppeteer.page.mainframe.md) and [frame.childFrames](./puppeteer.frame.childframes.md) methods.
<b>Signature:</b>
```typescript
@ -12,41 +14,79 @@ export declare class Frame
## Remarks
`Frame` object lifecycles are controlled by three events that are all dispatched on the page object:
- [PageEmittedEvents.FrameAttached](./puppeteer.pageemittedevents.frameattached.md)
- [PageEmittedEvents.FrameNavigated](./puppeteer.pageemittedevents.framenavigated.md)
- [PageEmittedEvents.FrameDetached](./puppeteer.pageemittedevents.framedetached.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.
## Example 1
An example of dumping frame tree:
```js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.google.com/chrome/browser/canary.html');
dumpFrameTree(page.mainFrame(), '');
await browser.close();
function dumpFrameTree(frame, indent) {
console.log(indent + frame.url());
for (const child of frame.childFrames()) {
dumpFrameTree(child, indent + ' ');
}
}
})();
```
## Example 2
An example of getting text from an iframe element:
```js
const frame = page.frames().find(frame => frame.name() === 'myframe');
const text = await frame.$eval('.selector', element => element.textContent);
console.log(text);
```
## Methods
| Method | Modifiers | Description |
| --- | --- | --- |
| [\_detach()](./puppeteer.frame._detach.md) | | |
| [\_navigated(framePayload)](./puppeteer.frame._navigated.md) | | |
| [\_navigatedWithinDocument(url)](./puppeteer.frame._navigatedwithindocument.md) | | |
| [\_onLifecycleEvent(loaderId, name)](./puppeteer.frame._onlifecycleevent.md) | | |
| [\_onLoadingStopped()](./puppeteer.frame._onloadingstopped.md) | | |
| [$(selector)](./puppeteer.frame._.md) | | |
| [$$(selector)](./puppeteer.frame.__.md) | | |
| [$(selector)](./puppeteer.frame._.md) | | This method queries the frame for the given selector. |
| [$$(selector)](./puppeteer.frame.__.md) | | This runs <code>document.querySelectorAll</code> in the frame and returns the result. |
| [$$eval(selector, pageFunction, args)](./puppeteer.frame.__eval.md) | | |
| [$eval(selector, pageFunction, args)](./puppeteer.frame._eval.md) | | |
| [$x(expression)](./puppeteer.frame._x.md) | | |
| [addScriptTag(options)](./puppeteer.frame.addscripttag.md) | | |
| [addStyleTag(options)](./puppeteer.frame.addstyletag.md) | | |
| [$x(expression)](./puppeteer.frame._x.md) | | This method evaluates the given XPath expression and returns the results. |
| [addScriptTag(options)](./puppeteer.frame.addscripttag.md) | | Adds a <code>&lt;script&gt;</code> tag into the page with the desired url or content. |
| [addStyleTag(options)](./puppeteer.frame.addstyletag.md) | | Adds a <code>&lt;link rel=&quot;stylesheet&quot;&gt;</code> tag into the page with the desired url or a <code>&lt;style type=&quot;text/css&quot;&gt;</code> tag with the content. |
| [childFrames()](./puppeteer.frame.childframes.md) | | |
| [click(selector, options)](./puppeteer.frame.click.md) | | |
| [click(selector, options)](./puppeteer.frame.click.md) | | This method clicks the first element found that matches <code>selector</code>. |
| [content()](./puppeteer.frame.content.md) | | |
| [evaluate(pageFunction, args)](./puppeteer.frame.evaluate.md) | | |
| [evaluateHandle(pageFunction, args)](./puppeteer.frame.evaluatehandle.md) | | |
| [executionContext()](./puppeteer.frame.executioncontext.md) | | |
| [focus(selector)](./puppeteer.frame.focus.md) | | |
| [focus(selector)](./puppeteer.frame.focus.md) | | This method fetches an element with <code>selector</code> and focuses it. |
| [goto(url, options)](./puppeteer.frame.goto.md) | | |
| [hover(selector)](./puppeteer.frame.hover.md) | | |
| [hover(selector)](./puppeteer.frame.hover.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.mouse](./puppeteer.page.mouse.md) to hover over the center of the element. |
| [isDetached()](./puppeteer.frame.isdetached.md) | | |
| [name()](./puppeteer.frame.name.md) | | |
| [parentFrame()](./puppeteer.frame.parentframe.md) | | |
| [select(selector, values)](./puppeteer.frame.select.md) | | |
| [setContent(html, options)](./puppeteer.frame.setcontent.md) | | |
| [tap(selector)](./puppeteer.frame.tap.md) | | |
| [select(selector, values)](./puppeteer.frame.select.md) | | Triggers a <code>change</code> and <code>input</code> event once all the provided options have been selected. |
| [setContent(html, options)](./puppeteer.frame.setcontent.md) | | Set the content of the frame. |
| [tap(selector)](./puppeteer.frame.tap.md) | | This method fetches an element with <code>selector</code>, scrolls it into view if needed, and then uses [Page.touchscreen](./puppeteer.page.touchscreen.md) to tap in the center of the element. |
| [title()](./puppeteer.frame.title.md) | | |
| [type(selector, text, options)](./puppeteer.frame.type.md) | | |
| [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) | | |
| [waitFor(selectorOrFunctionOrTimeout, options, args)](./puppeteer.frame.waitfor.md) | | |
| [waitForFunction(pageFunction, options, args)](./puppeteer.frame.waitforfunction.md) | | |

View File

@ -13,3 +13,11 @@ name(): string;
string
the frame's `name` attribute as specified in the tag.
## Remarks
If the name is empty, it returns the `id` attribute instead.
Note: This value is calculated once when the frame is created, and will not update if the attribute is changed later.

View File

@ -13,3 +13,5 @@ parentFrame(): Frame | null;
[Frame](./puppeteer.frame.md) \| null
the parent `Frame`<!-- -->, if any. Detached and main frames return `null`<!-- -->.

View File

@ -4,6 +4,8 @@
## Frame.select() method
Triggers a `change` and `input` event once all the provided options have been selected.
<b>Signature:</b>
```typescript
@ -14,10 +16,25 @@ select(selector: string, ...values: string[]): Promise<string[]>;
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| values | string\[\] | |
| selector | string | a selector to query the frame for |
| values | string\[\] | an array of values to select. If the <code>&lt;select&gt;</code> has the <code>multiple</code> attribute, all values are considered, otherwise only the first one is taken into account. |
<b>Returns:</b>
Promise&lt;string\[\]&gt;
the list of values that were successfully selected.
## Remarks
If there's no `<select>` element matching `selector`<!-- -->, the method throws an error.
## Example
```js
frame.select('select#colors', 'blue'); // single selection
frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections
```

View File

@ -4,6 +4,8 @@
## Frame.setContent() method
Set the content of the frame.
<b>Signature:</b>
```typescript
@ -17,8 +19,8 @@ setContent(html: string, options?: {
| Parameter | Type | Description |
| --- | --- | --- |
| html | string | |
| options | { timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)<!-- -->\[\]; } | |
| html | string | HTML markup to assign to the page. |
| options | { timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)<!-- -->\[\]; } | options to configure how long before timing out and at what point to consider the content setting successful. |
<b>Returns:</b>

View File

@ -4,6 +4,8 @@
## 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.
<b>Signature:</b>
```typescript
@ -14,9 +16,15 @@ tap(selector: string): Promise<void>;
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| selector | string | the selector to tap. |
<b>Returns:</b>
Promise&lt;void&gt;
a promise that resolves when the element has been tapped.
## Remarks
If there's no element matching `selector`<!-- -->, the method throws an error.

View File

@ -13,3 +13,5 @@ title(): Promise<string>;
Promise&lt;string&gt;
the frame's title.

View File

@ -4,6 +4,8 @@
## Frame.type() method
Sends a `keydown`<!-- -->, `keypress`<!-- -->/`input`<!-- -->, and `keyup` event for each character in the text.
<b>Signature:</b>
```typescript
@ -16,11 +18,26 @@ type(selector: string, text: string, options?: {
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| text | string | |
| options | { delay: number; } | |
| selector | string | the selector for the element to type into. If there are multiple the first will be used. |
| text | string | text to type into the element |
| options | { delay: number; } | takes one option, <code>delay</code>, which sets the time to wait between key presses in milliseconds. Defaults to <code>0</code>. |
<b>Returns:</b>
Promise&lt;void&gt;
a promise that resolves when the typing is complete.
## Remarks
To press a special key, like `Control` or `ArrowDown`<!-- -->, use [Keyboard.press()](./puppeteer.keyboard.press.md)<!-- -->.
## Example
```js
await frame.type('#mytextarea', 'Hello'); // Types instantly
await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
```

View File

@ -13,3 +13,5 @@ url(): string;
string
the frame's URL.

View File

@ -14,11 +14,19 @@ waitFor(selectorOrFunctionOrTimeout: string | number | Function, options?: {}, .
| Parameter | Type | Description |
| --- | --- | --- |
| selectorOrFunctionOrTimeout | string \| number \| Function | |
| options | {} | |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | |
| selectorOrFunctionOrTimeout | string \| number \| Function | a selector, predicate or timeout to wait for. |
| options | {} | optional waiting parameters. |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | arguments to pass to <code>pageFunction</code>. |
<b>Returns:</b>
Promise&lt;[JSHandle](./puppeteer.jshandle.md) \| null&gt;
## Remarks
This method behaves differently depending on the first parameter. If it's a `string`<!-- -->, it will be treated as a `selector` or `xpath` (if the string starts with `//`<!-- -->). This method then is a shortcut for [Frame.waitForSelector()](./puppeteer.frame.waitforselector.md) or [Frame.waitForXPath()](./puppeteer.frame.waitforxpath.md)<!-- -->.
If the first argument is a function this method is a shortcut for [Frame.waitForFunction()](./puppeteer.frame.waitforfunction.md)<!-- -->.
If the first argument is a `number`<!-- -->, it's treated as a timeout in milliseconds and the method returns a promise which resolves after the timeout.

View File

@ -7,21 +7,52 @@
<b>Signature:</b>
```typescript
waitForFunction(pageFunction: Function | string, options?: {
polling?: string | number;
timeout?: number;
}, ...args: SerializableOrJSHandle[]): Promise<JSHandle>;
waitForFunction(pageFunction: Function | string, options?: FrameWaitForFunctionOptions, ...args: SerializableOrJSHandle[]): Promise<JSHandle>;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| pageFunction | Function \| string | |
| options | { polling?: string \| number; timeout?: number; } | |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | |
| pageFunction | Function \| string | the function to evaluate in the frame context. |
| options | [FrameWaitForFunctionOptions](./puppeteer.framewaitforfunctionoptions.md) | options to configure the polling method and timeout. |
| args | [SerializableOrJSHandle](./puppeteer.serializableorjshandle.md)<!-- -->\[\] | arguments to pass to the <code>pageFunction</code>. |
<b>Returns:</b>
Promise&lt;[JSHandle](./puppeteer.jshandle.md)<!-- -->&gt;
the promise which resolve when the `pageFunction` returns a truthy value.
## Remarks
## Example
The `waitForFunction` can be used to observe viewport size change:
```js
const puppeteer = require('puppeteer');
(async () => {
. const browser = await puppeteer.launch();
. const page = await browser.newPage();
. const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
. page.setViewport({width: 50, height: 50});
. await watchDog;
. await browser.close();
})();
```
To pass arguments from Node.js to the predicate of `page.waitForFunction` function:
```js
const selector = '.foo';
await frame.waitForFunction(
selector => !!document.querySelector(selector),
{}, // empty options object
selector
);
```

View File

@ -17,9 +17,26 @@ waitForNavigation(options?: {
| Parameter | Type | Description |
| --- | --- | --- |
| options | { timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)<!-- -->\[\]; } | |
| options | { timeout?: number; waitUntil?: [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md) \| [PuppeteerLifeCycleEvent](./puppeteer.puppeteerlifecycleevent.md)<!-- -->\[\]; } | options to configure when the navigation is consided finished. |
<b>Returns:</b>
Promise&lt;[HTTPResponse](./puppeteer.httpresponse.md) \| null&gt;
a promise that resolves when the frame navigates to a new URL.
## Remarks
This resolves when the frame navigates to a new URL. It is useful for when you run code which will indirectly cause the frame to navigate. Consider this example:
```js
const [response] = await Promise.all([
// The navigation promise resolves after navigation has finished
frame.waitForNavigation(),
// Clicking the link will indirectly cause a navigation
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

@ -14,10 +14,40 @@ waitForSelector(selector: string, options?: WaitForSelectorOptions): Promise<Ele
| Parameter | Type | Description |
| --- | --- | --- |
| selector | string | |
| options | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | |
| selector | string | the selector to wait for. |
| options | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | options to define if the element should be visible and how long to wait before timing out. |
<b>Returns:</b>
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md) \| null&gt;
a promise which resolves when an element matching the selector string is added to the DOM.
## Remarks
Wait for the `selector` to appear in page. If at the moment of calling the method the `selector` already exists, the method will return immediately. If the selector doesn't appear after the `timeout` milliseconds of waiting, the function will throw.
This method works across navigations.
## Example
```js
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();
})();
```

View File

@ -14,10 +14,16 @@ waitForXPath(xpath: string, options?: WaitForSelectorOptions): Promise<ElementHa
| Parameter | Type | Description |
| --- | --- | --- |
| xpath | string | |
| options | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | |
| xpath | string | the XPath expression to wait for. |
| options | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | options to configure the visiblity of the element and how long to wait before timing out. |
<b>Returns:</b>
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md) \| null&gt;
## Remarks
Wait for the `xpath` to appear in page. If at the moment of calling the method the `xpath` already exists, the method will return immediately. If the xpath doesn't appear after the `timeout` milliseconds of waiting, the function will throw.
For a code example, see the example for [Frame.waitForSelector()](./puppeteer.frame.waitforselector.md)<!-- -->. That function behaves identically other than taking a CSS selector rather than an XPath.

View File

@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) &gt; [content](./puppeteer.frameaddscripttagoptions.content.md)
## FrameAddScriptTagOptions.content property
Raw JavaScript content to be injected into the frame.
<b>Signature:</b>
```typescript
content?: string;
```

View File

@ -0,0 +1,22 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md)
## FrameAddScriptTagOptions interface
<b>Signature:</b>
```typescript
export interface FrameAddScriptTagOptions
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [content](./puppeteer.frameaddscripttagoptions.content.md) | string | Raw JavaScript content to be injected into the frame. |
| [path](./puppeteer.frameaddscripttagoptions.path.md) | string | The path to a JavaScript file to be injected into the frame. |
| [type](./puppeteer.frameaddscripttagoptions.type.md) | string | Set the script's <code>type</code>. Use <code>module</code> in order to load an ES2015 module. |
| [url](./puppeteer.frameaddscripttagoptions.url.md) | string | the URL of the script to be added. |

View File

@ -0,0 +1,18 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) &gt; [path](./puppeteer.frameaddscripttagoptions.path.md)
## FrameAddScriptTagOptions.path property
The path to a JavaScript file to be injected into the frame.
<b>Signature:</b>
```typescript
path?: string;
```
## Remarks
If `path` is a relative path, it is resolved relative to the current working directory (`process.cwd()` in Node.js).

View File

@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) &gt; [type](./puppeteer.frameaddscripttagoptions.type.md)
## FrameAddScriptTagOptions.type property
Set the script's `type`<!-- -->. Use `module` in order to load an ES2015 module.
<b>Signature:</b>
```typescript
type?: string;
```

View File

@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) &gt; [url](./puppeteer.frameaddscripttagoptions.url.md)
## FrameAddScriptTagOptions.url property
the URL of the script to be added.
<b>Signature:</b>
```typescript
url?: string;
```

View File

@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) &gt; [content](./puppeteer.frameaddstyletagoptions.content.md)
## FrameAddStyleTagOptions.content property
Raw CSS content to be injected into the frame.
<b>Signature:</b>
```typescript
content?: string;
```

View File

@ -0,0 +1,21 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md)
## FrameAddStyleTagOptions interface
<b>Signature:</b>
```typescript
export interface FrameAddStyleTagOptions
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [content](./puppeteer.frameaddstyletagoptions.content.md) | string | Raw CSS content to be injected into the frame. |
| [path](./puppeteer.frameaddstyletagoptions.path.md) | string | The path to a CSS file to be injected into the frame. |
| [url](./puppeteer.frameaddstyletagoptions.url.md) | string | the URL of the CSS file to be added. |

View File

@ -0,0 +1,18 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) &gt; [path](./puppeteer.frameaddstyletagoptions.path.md)
## FrameAddStyleTagOptions.path property
The path to a CSS file to be injected into the frame.
<b>Signature:</b>
```typescript
path?: string;
```
## Remarks
If `path` is a relative path, it is resolved relative to the current working directory (`process.cwd()` in Node.js).

View File

@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) &gt; [url](./puppeteer.frameaddstyletagoptions.url.md)
## FrameAddStyleTagOptions.url property
the URL of the CSS file to be added.
<b>Signature:</b>
```typescript
url?: string;
```

View File

@ -0,0 +1,20 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameWaitForFunctionOptions](./puppeteer.framewaitforfunctionoptions.md)
## FrameWaitForFunctionOptions interface
<b>Signature:</b>
```typescript
export interface FrameWaitForFunctionOptions
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [polling](./puppeteer.framewaitforfunctionoptions.polling.md) | string \| number | An interval at which the <code>pageFunction</code> is executed, defaults to <code>raf</code>. If <code>polling</code> is a number, then it is treated as an interval in milliseconds at which the function would be executed. If <code>polling</code> is a string, then it can be one of the following values:<!-- -->- <code>raf</code> - to constantly execute <code>pageFunction</code> in <code>requestAnimationFrame</code> callback. This is the tightest polling mode which is suitable to observe styling changes.<!-- -->- <code>mutation</code> - to execute <code>pageFunction</code> on every DOM mutation. |
| [timeout](./puppeteer.framewaitforfunctionoptions.timeout.md) | number | Maximum time to wait in milliseconds. Defaults to <code>30000</code> (30 seconds). Pass <code>0</code> to disable the timeout. Puppeteer's default timeout can be changed using [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md)<!-- -->. |

View File

@ -0,0 +1,17 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameWaitForFunctionOptions](./puppeteer.framewaitforfunctionoptions.md) &gt; [polling](./puppeteer.framewaitforfunctionoptions.polling.md)
## FrameWaitForFunctionOptions.polling property
An interval at which the `pageFunction` is executed, defaults to `raf`<!-- -->. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. If `polling` is a string, then it can be one of the following values:
- `raf` - to constantly execute `pageFunction` in `requestAnimationFrame` callback. This is the tightest polling mode which is suitable to observe styling changes.
- `mutation` - to execute `pageFunction` on every DOM mutation.
<b>Signature:</b>
```typescript
polling?: string | number;
```

View File

@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [FrameWaitForFunctionOptions](./puppeteer.framewaitforfunctionoptions.md) &gt; [timeout](./puppeteer.framewaitforfunctionoptions.timeout.md)
## FrameWaitForFunctionOptions.timeout property
Maximum time to wait in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable the timeout. Puppeteer's default timeout can be changed using [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md)<!-- -->.
<b>Signature:</b>
```typescript
timeout?: number;
```

View File

@ -20,7 +20,7 @@
| [EventEmitter](./puppeteer.eventemitter.md) | The EventEmitter class that many Puppeteer classes extend. |
| [ExecutionContext](./puppeteer.executioncontext.md) | This class represents a context for JavaScript execution. A \[Page\] might have many execution contexts: - each [frame](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) has "default" execution context that is always created after frame is attached to DOM. This context is returned by the method. - [Extension](https://developer.chrome.com/extensions)<!-- -->'s content scripts create additional execution contexts.<!-- -->Besides pages, execution contexts can be found in [workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)<!-- -->. |
| [FileChooser](./puppeteer.filechooser.md) | File choosers let you react to the page requesting for a file. |
| [Frame](./puppeteer.frame.md) | |
| [Frame](./puppeteer.frame.md) | At every point of time, page exposes its current frame tree via the [page.mainFrame](./puppeteer.page.mainframe.md) and [frame.childFrames](./puppeteer.frame.childframes.md) methods. |
| [HTTPRequest](./puppeteer.httprequest.md) | Represents an HTTP request sent by a page. |
| [HTTPResponse](./puppeteer.httpresponse.md) | The HTTPResponse class represents responses which are received by the [Page](./puppeteer.page.md) class. |
| [JSHandle](./puppeteer.jshandle.md) | Represents an in-page JavaScript object. JSHandles can be created with the [page.evaluateHandle](./puppeteer.page.evaluatehandle.md) method. |
@ -59,6 +59,9 @@
| [CoverageEntry](./puppeteer.coverageentry.md) | The CoverageEntry class represents one entry of the coverage report. |
| [Credentials](./puppeteer.credentials.md) | |
| [CSSCoverageOptions](./puppeteer.csscoverageoptions.md) | Set of configurable options for CSS coverage. |
| [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) | |
| [FrameAddStyleTagOptions](./puppeteer.frameaddstyletagoptions.md) | |
| [FrameWaitForFunctionOptions](./puppeteer.framewaitforfunctionoptions.md) | |
| [GeolocationOptions](./puppeteer.geolocationoptions.md) | |
| [JSCoverageOptions](./puppeteer.jscoverageoptions.md) | Set of configurable options for JS coverage. |
| [JSONObject](./puppeteer.jsonobject.md) | |

View File

@ -14,10 +14,49 @@ evaluate<ReturnType extends any>(pageFunction: Function | string, ...args: unkno
| Parameter | Type | Description |
| --- | --- | --- |
| pageFunction | Function \| string | |
| args | unknown\[\] | |
| pageFunction | Function \| string | a function that is run within the page |
| args | unknown\[\] | arguments to be passed to the pageFunction |
<b>Returns:</b>
Promise&lt;ReturnType&gt;
the return value of `pageFunction`<!-- -->.
## Remarks
Evaluates a function in the page's context and returns the result.
If the function passed to `page.evaluteHandle` returns a Promise, the function will wait for the promise to resolve and return its value.
## Example 1
```js
const result = await frame.evaluate(() => {
return Promise.resolve(8 * 7);
});
console.log(result); // prints "56"
```
You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
## Example 2
```
const aHandle = await page.evaluate('1 + 2');
```
## Example 3
[ElementHandle](./puppeteer.elementhandle.md) instances (including [JSHandle](./puppeteer.jshandle.md)<!-- -->s) can be passed as arguments to the `pageFunction`<!-- -->:
```
const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();
```

View File

@ -386,6 +386,123 @@ export class FrameManager extends EventEmitter {
/**
* @public
*/
export interface FrameWaitForFunctionOptions {
/**
* An interval at which the `pageFunction` is executed, defaults to `raf`. If
* `polling` is a number, then it is treated as an interval in milliseconds at
* which the function would be executed. If `polling` is a string, then it can
* be one of the following values:
*
* - `raf` - to constantly execute `pageFunction` in `requestAnimationFrame`
* callback. This is the tightest polling mode which is suitable to observe
* styling changes.
*
* - `mutation` - to execute `pageFunction` on every DOM mutation.
*/
polling?: string | number;
/**
* Maximum time to wait in milliseconds. Defaults to `30000` (30 seconds).
* Pass `0` to disable the timeout. Puppeteer's default timeout can be changed
* using {@link Page.setDefaultTimeout}.
*/
timeout?: number;
}
/**
* @public
*/
export interface FrameAddScriptTagOptions {
/**
* the URL of the script to be added.
*/
url?: string;
/**
* The path to a JavaScript file to be injected into the frame.
* @remarks
* If `path` is a relative path, it is resolved relative to the current
* working directory (`process.cwd()` in Node.js).
*/
path?: string;
/**
* Raw JavaScript content to be injected into the frame.
*/
content?: string;
/**
* Set the script's `type`. Use `module` in order to load an ES2015 module.
*/
type?: string;
}
/**
* @public
*/
export interface FrameAddStyleTagOptions {
/**
* the URL of the CSS file to be added.
*/
url?: string;
/**
* The path to a CSS file to be injected into the frame.
* @remarks
* If `path` is a relative path, it is resolved relative to the current
* working directory (`process.cwd()` in Node.js).
*/
path?: string;
/**
* Raw CSS content to be injected into the frame.
*/
content?: string;
}
/**
* At every point of time, page exposes its current frame tree via the
* {@link Page.mainFrame | page.mainFrame} and
* {@link Frame.childFrames | frame.childFrames} methods.
*
* @remarks
*
* `Frame` object lifecycles are controlled by three events that are all
* dispatched on the page object:
*
* - {@link PageEmittedEvents.FrameAttached}
*
* - {@link PageEmittedEvents.FrameNavigated}
*
* - {@link PageEmittedEvents.FrameDetached}
*
* @Example
* An example of dumping frame tree:
*
* ```js
* const puppeteer = require('puppeteer');
*
* (async () => {
* const browser = await puppeteer.launch();
* const page = await browser.newPage();
* await page.goto('https://www.google.com/chrome/browser/canary.html');
* dumpFrameTree(page.mainFrame(), '');
* await browser.close();
*
* function dumpFrameTree(frame, indent) {
* console.log(indent + frame.url());
* for (const child of frame.childFrames()) {
* dumpFrameTree(child, indent + ' ');
* }
* }
* })();
* ```
*
* @Example
* An example of getting text from an iframe element:
*
* ```js
* const frame = page.frames().find(frame => frame.name() === 'myframe');
* const text = await frame.$eval('.selector', element => element.textContent);
* console.log(text);
* ```
*
* @public
*/
export class Frame {
/**
* @internal
@ -455,6 +572,44 @@ export class Frame {
if (this._parentFrame) this._parentFrame._childFrames.add(this);
}
/**
* @remarks
*
* `frame.goto` 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.
*
* `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 {@link HTTPResponse.status}.
*
* 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 {@link https://bugs.chromium.org/p/chromium/issues/detail?id=761295 | upstream
* issue}.
*
* @param url - the URL to navigate the frame to. This should include the
* scheme, e.g. `https://`.
* @param options - navigation options. `waitUntil` is useful to define when
* the navigation should be considered successful - see the docs for
* {@link PuppeteerLifeCycleEvent} for more details.
*
* @returns 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.
*/
async goto(
url: string,
options: {
@ -466,6 +621,27 @@ export class Frame {
return await this._frameManager.navigateFrame(this, url, options);
}
/**
* @remarks
*
* This resolves when the frame navigates to a new URL. It is useful for when
* you run code which will indirectly cause the frame to navigate. Consider
* this example:
*
* ```js
* const [response] = await Promise.all([
* // The navigation promise resolves after navigation has finished
* frame.waitForNavigation(),
* // Clicking the link will indirectly cause a navigation
* frame.click('a.my-link'),
* ]);
* ```
*
* Usage of the {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API} to change the URL is considered a navigation.
*
* @param options - options to configure when the navigation is consided finished.
* @returns a promise that resolves when the frame navigates to a new URL.
*/
async waitForNavigation(
options: {
timeout?: number;
@ -475,10 +651,26 @@ export class Frame {
return await this._frameManager.waitForFrameNavigation(this, options);
}
/**
* @returns a promise that resolves to the frame's default execution context.
*/
executionContext(): Promise<ExecutionContext> {
return this._mainWorld.executionContext();
}
/**
* @remarks
*
* The only difference between {@link Frame.evaluate} and
* `frame.evaluateHandle` is that `evaluateHandle` will return the value
* wrapped in an in-page object.
*
* This method behaves identically to {@link Page.evaluateHandle} except it's
* run within the context of the `frame`, rather than the entire page.
*
* @param pageFunction - a function that is run within the frame
* @param args - arguments to be passed to the pageFunction
*/
async evaluateHandle<HandlerType extends JSHandle = JSHandle>(
pageFunction: EvaluateHandleFn,
...args: SerializableOrJSHandle[]
@ -486,6 +678,15 @@ export class Frame {
return this._mainWorld.evaluateHandle<HandlerType>(pageFunction, ...args);
}
/**
* @remarks
*
* This method behaves identically to {@link Page.evaluate} except it's run
* within the context of the `frame`, rather than the entire page.
*
* @param pageFunction - a function that is run within the frame
* @param args - arguments to be passed to the pageFunction
*/
async evaluate<ReturnType extends any>(
pageFunction: Function | string,
...args: unknown[]
@ -493,14 +694,45 @@ export class Frame {
return this._mainWorld.evaluate<ReturnType>(pageFunction, ...args);
}
/**
* This method queries the frame for the given selector.
*
* @param selector - a selector to query for.
* @returns A promise which resolves to an `ElementHandle` pointing at the
* element, or `null` if it was not found.
*/
async $(selector: string): Promise<ElementHandle | null> {
return this._mainWorld.$(selector);
}
/**
* This method evaluates the given XPath expression and returns the results.
*
* @param expression - the XPath expression to evaluate.
*/
async $x(expression: string): Promise<ElementHandle[]> {
return this._mainWorld.$x(expression);
}
/**
* @remarks
*
* This method runs `document.querySelector` within
* the frame and passes it as the first argument to `pageFunction`.
*
* If `pageFunction` returns a Promise, then `frame.$eval` would wait for
* the promise to resolve and return its value.
*
* @example
*
* ```js
* const searchValue = await frame.$eval('#search', el => el.value);
* ```
*
* @param selector - the selector to query for
* @param pageFunction - the function to be evaluated in the frame's context
* @param args - additional arguments to pass to `pageFuncton`
*/
async $eval<ReturnType>(
selector: string,
pageFunction: (
@ -512,6 +744,25 @@ export class Frame {
return this._mainWorld.$eval<ReturnType>(selector, pageFunction, ...args);
}
/**
* @remarks
*
* This method runs `Array.from(document.querySelectorAll(selector))` within
* the frame and passes it as the first argument to `pageFunction`.
*
* If `pageFunction` returns a Promise, then `frame.$$eval` would wait for
* the promise to resolve and return its value.
*
* @example
*
* ```js
* const divsCounts = await frame.$$eval('div', divs => divs.length);
* ```
*
* @param selector - the selector to query for
* @param pageFunction - the function to be evaluated in the frame's context
* @param args - additional arguments to pass to `pageFuncton`
*/
async $$eval<ReturnType>(
selector: string,
pageFunction: (
@ -523,14 +774,30 @@ export class Frame {
return this._mainWorld.$$eval<ReturnType>(selector, pageFunction, ...args);
}
/**
* This runs `document.querySelectorAll` in the frame and returns the result.
*
* @param selector - a selector to search for
* @returns An array of element handles pointing to the found frame elements.
*/
async $$(selector: string): Promise<ElementHandle[]> {
return this._mainWorld.$$(selector);
}
/**
* @returns the full HTML contents of the frame, including the doctype.
*/
async content(): Promise<string> {
return this._secondaryWorld.content();
}
/**
* Set the content of the frame.
*
* @param html - HTML markup to assign to the page.
* @param options - options to configure how long before timing out and at
* what point to consider the content setting successful.
*/
async setContent(
html: string,
options: {
@ -541,43 +808,101 @@ export class Frame {
return this._secondaryWorld.setContent(html, options);
}
/**
* @remarks
*
* If the name is empty, it returns the `id` attribute instead.
*
* Note: This value is calculated once when the frame is created, and will not
* update if the attribute is changed later.
*
* @returns the frame's `name` attribute as specified in the tag.
*/
name(): string {
return this._name || '';
}
/**
* @returns the frame's URL.
*/
url(): string {
return this._url;
}
/**
* @returns the parent `Frame`, if any. Detached and main frames return `null`.
*/
parentFrame(): Frame | null {
return this._parentFrame;
}
/**
* @returns an array of child frames.
*/
childFrames(): Frame[] {
return Array.from(this._childFrames);
}
/**
* @returns `true` if the frame has been detached, or `false` otherwise.
*/
isDetached(): boolean {
return this._detached;
}
async addScriptTag(options: {
url?: string;
path?: string;
content?: string;
type?: string;
}): Promise<ElementHandle> {
/**
* Adds a `<script>` tag into the page with the desired url or content.
*
* @param options - configure the script to add to the page.
*
* @returns a promise that resolves to the added tag when the script's
* `onload` event fires or when the script content was injected into the
* frame.
*/
async addScriptTag(
options: FrameAddScriptTagOptions
): Promise<ElementHandle> {
return this._mainWorld.addScriptTag(options);
}
async addStyleTag(options: {
url?: string;
path?: string;
content?: string;
}): Promise<ElementHandle> {
/**
* Adds a `<link rel="stylesheet">` tag into the page with the desired url or
* a `<style type="text/css">` tag with the content.
*
* @param options - configure the CSS to add to the page.
*
* @returns 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.
*/
async addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle> {
return this._mainWorld.addStyleTag(options);
}
/**
*
* This method clicks the first element found that matches `selector`.
*
* @remarks
*
* This method scrolls the element into view if needed, and then uses
* {@link Page.mouse} to click in the center of the element. If there's no
* element matching `selector`, the method throws an error.
*
* Bear in mind that if `click()` triggers a navigation event and there's a
* separate `page.waitForNavigation()` promise to be resolved, you may end up
* with a race condition that yields unexpected results. The correct pattern
* for click and wait for navigation is the following:
*
* ```javascript
* const [response] = await Promise.all([
* page.waitForNavigation(waitOptions),
* frame.click(selector, clickOptions),
* ]);
* ```
* @param selector - the selector to search for to click. If there are
* multiple elements, the first will be clicked.
*/
async click(
selector: string,
options: {
@ -589,22 +914,97 @@ export class Frame {
return this._secondaryWorld.click(selector, options);
}
/**
* This method fetches an element with `selector` and focuses it.
*
* @remarks
* If there's no element matching `selector`, the method throws an error.
*
* @param selector - the selector for the element to focus. If there are
* multiple elements, the first will be focused.
*/
async focus(selector: string): Promise<void> {
return this._secondaryWorld.focus(selector);
}
/**
* This method fetches an element with `selector`, scrolls it into view if
* needed, and then uses {@link Page.mouse} to hover over the center of the
* element.
*
* @remarks
* If there's no element matching `selector`, the method throws an
*
* @param selector - the selector for the element to hover. If there are
* multiple elements, the first will be hovered.
*/
async hover(selector: string): Promise<void> {
return this._secondaryWorld.hover(selector);
}
/**
* Triggers a `change` and `input` event once all the provided options have
* been selected.
*
* @remarks
*
* If there's no `<select>` element matching `selector`, the
* method throws an error.
*
* @example
* ```js
* frame.select('select#colors', 'blue'); // single selection
* frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections
* ```
*
* @param selector - a selector to query the frame for
* @param values - an array of values to select. If the `<select>` has the
* `multiple` attribute, all values are considered, otherwise only the first
* one is taken into account.
* @returns the list of values that were successfully selected.
*/
select(selector: string, ...values: string[]): Promise<string[]> {
return this._secondaryWorld.select(selector, ...values);
}
/**
* This method fetches an element with `selector`, scrolls it into view if
* needed, and then uses {@link Page.touchscreen} to tap in the center of the
* element.
*
* @remarks
*
* If there's no element matching `selector`, the method throws an error.
*
* @param selector - the selector to tap.
* @returns a promise that resolves when the element has been tapped.
*/
async tap(selector: string): Promise<void> {
return this._secondaryWorld.tap(selector);
}
/**
* Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character
* in the text.
*
* @remarks
* To press a special key, like `Control` or `ArrowDown`, use
* {@link Keyboard.press}.
*
* @example
* ```js
* await frame.type('#mytextarea', 'Hello'); // Types instantly
* await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
* ```
*
* @param selector - the selector for the element to type into. If there are
* multiple the first will be used.
* @param text - text to type into the element
* @param options - takes one option, `delay`, which sets the time to wait
* between key presses in milliseconds. Defaults to `0`.
*
* @returns a promise that resolves when the typing is complete.
*/
async type(
selector: string,
text: string,
@ -613,6 +1013,26 @@ export class Frame {
return this._mainWorld.type(selector, text, options);
}
/**
* @remarks
*
* This method behaves differently depending on the first parameter. If it's a
* `string`, it will be treated as a `selector` or `xpath` (if the string
* starts with `//`). This method then is a shortcut for
* {@link Frame.waitForSelector} or {@link Frame.waitForXPath}.
*
* If the first argument is a function this method is a shortcut for
* {@link Frame.waitForFunction}.
*
* If the first argument is a `number`, it's treated as a timeout in
* milliseconds and the method returns a promise which resolves after the
* timeout.
*
* @param selectorOrFunctionOrTimeout - a selector, predicate or timeout to
* wait for.
* @param options - optional waiting parameters.
* @param args - arguments to pass to `pageFunction`.
*/
waitFor(
selectorOrFunctionOrTimeout: string | number | Function,
options: {} = {},
@ -643,6 +1063,41 @@ export class Frame {
);
}
/**
* @remarks
*
*
* Wait for the `selector` to appear in page. If at the moment of calling the
* method the `selector` already exists, the method will return immediately.
* If the selector doesn't appear after the `timeout` milliseconds of waiting,
* the function will throw.
*
* This method works across navigations.
*
* @example
* ```js
* 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 wait for.
* @param options - options to define if the element should be visible and how
* long to wait before timing out.
* @returns a promise which resolves when an element matching the selector
* string is added to the DOM.
*/
async waitForSelector(
selector: string,
options: WaitForSelectorOptions = {}
@ -658,6 +1113,21 @@ export class Frame {
return result;
}
/**
* @remarks
* Wait for the `xpath` to appear in page. If at the moment of calling the
* method the `xpath` already exists, the method will return immediately. If
* the xpath doesn't appear after the `timeout` milliseconds of waiting, the
* function will throw.
*
* For a code example, see the example for {@link Frame.waitForSelector}. That
* function behaves identically other than taking a CSS selector rather than
* an XPath.
*
* @param xpath - the XPath expression to wait for.
* @param options - options to configure the visiblity of the element and how
* long to wait before timing out.
*/
async waitForXPath(
xpath: string,
options: WaitForSelectorOptions = {}
@ -670,27 +1140,74 @@ export class Frame {
return result;
}
/**
* @remarks
*
* @example
*
* The `waitForFunction` can be used to observe viewport size change:
* ```js
* const puppeteer = require('puppeteer');
*
* (async () => {
* . const browser = await puppeteer.launch();
* . const page = await browser.newPage();
* . const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
* . page.setViewport({width: 50, height: 50});
* . await watchDog;
* . await browser.close();
* })();
* ```
*
* To pass arguments from Node.js to the predicate of `page.waitForFunction` function:
*
* ```js
* const selector = '.foo';
* await frame.waitForFunction(
* selector => !!document.querySelector(selector),
* {}, // empty options object
* selector
*);
* ```
*
* @param pageFunction - the function to evaluate in the frame context.
* @param options - options to configure the polling method and timeout.
* @param args - arguments to pass to the `pageFunction`.
* @returns the promise which resolve when the `pageFunction` returns a truthy value.
*/
waitForFunction(
pageFunction: Function | string,
options: { polling?: string | number; timeout?: number } = {},
options: FrameWaitForFunctionOptions = {},
...args: SerializableOrJSHandle[]
): Promise<JSHandle> {
return this._mainWorld.waitForFunction(pageFunction, options, ...args);
}
/**
* @returns the frame's title.
*/
async title(): Promise<string> {
return this._secondaryWorld.title();
}
/**
* @internal
*/
_navigated(framePayload: Protocol.Page.Frame): void {
this._name = framePayload.name;
this._url = framePayload.url;
}
/**
* @internal
*/
_navigatedWithinDocument(url: string): void {
this._url = url;
}
/**
* @internal
*/
_onLifecycleEvent(loaderId: string, name: string): void {
if (name === 'init') {
this._loaderId = loaderId;
@ -699,11 +1216,17 @@ export class Frame {
this._lifecycleEvents.add(name);
}
/**
* @internal
*/
_onLoadingStopped(): void {
this._lifecycleEvents.add('DOMContentLoaded');
this._lifecycleEvents.add('load');
}
/**
* @internal
*/
_detach(): void {
this._detached = true;
this._mainWorld._detach();

View File

@ -1494,6 +1494,47 @@ export class Page extends EventEmitter {
return this._viewport;
}
/**
* @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
*
* ```js
* const result = await frame.evaluate(() => {
* return Promise.resolve(8 * 7);
* });
* console.log(result); // prints "56"
* ```
*
* You can pass a string instead of a function (although functions are
* recommended as they are easier to debug and use with TypeScript):
*
* @example
* ```
* const aHandle = await page.evaluate('1 + 2');
* ```
*
* @example
*
* {@link ElementHandle} instances (including {@link JSHandle}s) can be passed
* as arguments to the `pageFunction`:
*
* ```
* const bodyHandle = await page.$('body');
* const html = await page.evaluate(body => body.innerHTML, bodyHandle);
* await bodyHandle.dispose();
* ```
*
* @param pageFunction - a function that is run within the page
* @param args - arguments to be passed to the pageFunction
*
* @returns the return value of `pageFunction`.
*/
async evaluate<ReturnType extends any>(
pageFunction: Function | string,
...args: unknown[]

View File

@ -770,6 +770,27 @@ function compareDocumentations(actual, expected) {
expectedName: 'ResponseForRequest',
},
],
[
'Method Frame.addScriptTag() options',
{
actualName: 'Object',
expectedName: 'FrameAddScriptTagOptions',
},
],
[
'Method Frame.addStyleTag() options',
{
actualName: 'Object',
expectedName: 'FrameAddStyleTagOptions',
},
],
[
'Method Frame.waitForFunction() options',
{
actualName: 'Object',
expectedName: 'FrameWaitForFunctionOptions',
},
],
]);
const expectedForSource = expectedNamingMismatches.get(source);