Skip to content

Commit

Permalink
chore: use injections for wait tasks (#8943)
Browse files Browse the repository at this point in the history
This PR refactors wait tasks to use injected scripts.
  • Loading branch information
jrandolf committed Sep 15, 2022
1 parent 8d5097d commit 7c4f41f
Show file tree
Hide file tree
Showing 21 changed files with 552 additions and 656 deletions.
8 changes: 4 additions & 4 deletions docs/api/puppeteer.framewaitforfunctionoptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export interface FrameWaitForFunctionOptions

## Properties

| Property | Modifiers | Type | Description |
| -------------------------------------------------------------- | --------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [polling?](./puppeteer.framewaitforfunctionoptions.polling.md) | | string \| number | <p><i>(Optional)</i> 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:</p><p>- <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.</p><p>- <code>mutation</code> - to execute <code>pageFunction</code> on every DOM mutation.</p> |
| [timeout?](./puppeteer.framewaitforfunctionoptions.timeout.md) | | number | <i>(Optional)</i> 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). |
| Property | Modifiers | Type | Description |
| -------------------------------------------------------------- | --------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [polling?](./puppeteer.framewaitforfunctionoptions.polling.md) | | 'raf' \| 'mutation' \| number | <p><i>(Optional)</i> 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:</p><p>- <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.</p><p>- <code>mutation</code> - to execute <code>pageFunction</code> on every DOM mutation.</p> |
| [timeout?](./puppeteer.framewaitforfunctionoptions.timeout.md) | | number | <i>(Optional)</i> 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). |
2 changes: 1 addition & 1 deletion docs/api/puppeteer.framewaitforfunctionoptions.polling.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ An interval at which the `pageFunction` is executed, defaults to `raf`. If `poll

```typescript
interface FrameWaitForFunctionOptions {
polling?: string | number;
polling?: 'raf' | 'mutation' | number;
}
```
2 changes: 1 addition & 1 deletion docs/api/puppeteer.innerparams.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ sidebar_label: InnerParams

```typescript
export declare type InnerParams<T extends unknown[]> = {
[K in keyof T]: FlattenHandle<T[K]>;
[K in keyof T]: FlattenHandle<FlattenLazyArg<FlattenHandle<T[K]>>>;
};
```

Expand Down
17 changes: 6 additions & 11 deletions docs/api/puppeteer.page.waitforfunction.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,24 @@ class Page {
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>
>(
pageFunction: Func | string,
options?: {
timeout?: number;
polling?: string | number;
},
options?: FrameWaitForFunctionOptions,
...args: Params
): Promise<HandleFor<Awaited<ReturnType<Func>>>>;
}
```

## Parameters

| Parameter | Type | Description |
| ------------ | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| pageFunction | Func \| string | Function to be evaluated in browser context |
| options | { timeout?: number; polling?: string \| number; } | <p><i>(Optional)</i> Optional waiting parameters</p><p>- <code>polling</code> - 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 polling 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 pageFunction on every DOM mutation. - <code>timeout</code> - maximum time to wait for in milliseconds. Defaults to <code>30000</code> (30 seconds). Pass <code>0</code> to disable timeout. The default value can be changed by using the [Page.setDefaultTimeout()](./puppeteer.page.setdefaulttimeout.md) method.</p> |
| args | Params | Arguments to pass to <code>pageFunction</code> |
| Parameter | Type | Description |
| ------------ | ------------------------------------------------------------------------- | ----------------------------------------------------------- |
| pageFunction | Func \| string | Function to be evaluated in browser context |
| options | [FrameWaitForFunctionOptions](./puppeteer.framewaitforfunctionoptions.md) | <i>(Optional)</i> Options for configuring waiting behavior. |
| args | Params | |

**Returns:**

Promise&lt;[HandleFor](./puppeteer.handlefor.md)&lt;Awaited&lt;ReturnType&lt;Func&gt;&gt;&gt;&gt;

A `Promise` which resolves to a JSHandle/ElementHandle of the the `pageFunction`'s return value.

## Example 1

The [Page.waitForFunction()](./puppeteer.page.waitforfunction.md) can be used to observe viewport size change:
Expand Down
36 changes: 16 additions & 20 deletions src/common/AriaQueryHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {assert} from '../util/assert.js';
import {CDPSession} from './Connection.js';
import {ElementHandle} from './ElementHandle.js';
import {Frame} from './Frame.js';
import {MAIN_WORLD, PageBinding, PUPPETEER_WORLD} from './IsolatedWorld.js';
import {MAIN_WORLD, PUPPETEER_WORLD} from './IsolatedWorld.js';
import {InternalQueryHandler} from './QueryHandler.js';

async function queryAXTree(
Expand Down Expand Up @@ -121,21 +121,20 @@ const waitFor: InternalQueryHandler['waitFor'] = async (
frame = elementOrFrame.frame;
element = await frame.worlds[PUPPETEER_WORLD].adoptHandle(elementOrFrame);
}
const binding: PageBinding = {
name: 'ariaQuerySelector',
pptrFunction: async (selector: string) => {
const id = await queryOneId(
element || (await frame.worlds[PUPPETEER_WORLD].document()),
selector
);
if (!id) {
return null;
}
return (await frame.worlds[PUPPETEER_WORLD].adoptBackendNode(
id
)) as ElementHandle<Node>;
},

const ariaQuerySelector = async (selector: string) => {
const id = await queryOneId(
element || (await frame.worlds[PUPPETEER_WORLD].document()),
selector
);
if (!id) {
return null;
}
return (await frame.worlds[PUPPETEER_WORLD].adoptBackendNode(
id
)) as ElementHandle<Node>;
};

const result = await frame.worlds[PUPPETEER_WORLD]._waitForSelectorInPage(
(_: Element, selector: string) => {
return (
Expand All @@ -147,16 +146,13 @@ const waitFor: InternalQueryHandler['waitFor'] = async (
element,
selector,
options,
binding
new Set([ariaQuerySelector])
);
if (element) {
await element.dispose();
}
if (!result) {
return null;
}
if (!(result instanceof ElementHandle)) {
await result.dispose();
await result?.dispose();
return null;
}
return result.frame.worlds[MAIN_WORLD].transferHandle(result);
Expand Down
10 changes: 7 additions & 3 deletions src/common/ExecutionContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {Protocol} from 'devtools-protocol';
import {CDPSession} from './Connection.js';
import {IsolatedWorld} from './IsolatedWorld.js';
import {JSHandle} from './JSHandle.js';
import {LazyArg} from './LazyArg.js';
import {EvaluateFunc, HandleFor} from './types.js';
import {
createJSHandle,
Expand Down Expand Up @@ -273,7 +274,7 @@ export class ExecutionContext {
callFunctionOnPromise = this._client.send('Runtime.callFunctionOn', {
functionDeclaration: functionText + '\n' + suffix + '\n',
executionContextId: this._contextId,
arguments: args.map(convertArgument.bind(this)),
arguments: await Promise.all(args.map(convertArgument.bind(this))),
returnByValue,
awaitPromise: true,
userGesture: true,
Expand All @@ -298,10 +299,13 @@ export class ExecutionContext {
? valueFromRemoteObject(remoteObject)
: createJSHandle(this, remoteObject);

function convertArgument(
async function convertArgument(
this: ExecutionContext,
arg: unknown
): Protocol.Runtime.CallArgument {
): Promise<Protocol.Runtime.CallArgument> {
if (arg instanceof LazyArg) {
arg = await arg.get();
}
if (typeof arg === 'bigint') {
// eslint-disable-line valid-typeof
return {unserializableValue: `${arg.toString()}n`};
Expand Down
3 changes: 1 addition & 2 deletions src/common/Frame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface FrameWaitForFunctionOptions {
*
* - `mutation` - to execute `pageFunction` on every DOM mutation.
*/
polling?: string | number;
polling?: 'raf' | 'mutation' | 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
Expand Down Expand Up @@ -664,7 +664,6 @@ export class Frame {
options: FrameWaitForFunctionOptions = {},
...args: Params
): Promise<HandleFor<Awaited<ReturnType<Func>>>> {
// TODO: Fix when NodeHandle has been added.
return this.worlds[MAIN_WORLD].waitForFunction(
pageFunction,
options,
Expand Down

0 comments on commit 7c4f41f

Please sign in to comment.