2022-07-05 13:41:43 +00:00
|
|
|
---
|
|
|
|
sidebar_label: ExecutionContext.evaluate
|
|
|
|
---
|
|
|
|
|
|
|
|
# ExecutionContext.evaluate() method
|
|
|
|
|
2022-08-11 09:45:35 +00:00
|
|
|
Evaluates the given function.
|
|
|
|
|
2022-07-05 13:41:43 +00:00
|
|
|
**Signature:**
|
|
|
|
|
|
|
|
```typescript
|
|
|
|
class ExecutionContext {
|
|
|
|
evaluate<
|
|
|
|
Params extends unknown[],
|
|
|
|
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>
|
|
|
|
>(
|
|
|
|
pageFunction: Func | string,
|
|
|
|
...args: Params
|
|
|
|
): Promise<Awaited<ReturnType<Func>>>;
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Parameters
|
|
|
|
|
2022-08-11 09:45:35 +00:00
|
|
|
| Parameter | Type | Description |
|
|
|
|
| ------------ | -------------- | ----------------------------------------------- |
|
|
|
|
| pageFunction | Func \| string | The function to evaluate. |
|
|
|
|
| args | Params | Additional arguments to pass into the function. |
|
2022-07-05 13:41:43 +00:00
|
|
|
|
|
|
|
**Returns:**
|
|
|
|
|
|
|
|
Promise<Awaited<ReturnType<Func>>>
|
|
|
|
|
2022-08-11 09:45:35 +00:00
|
|
|
The result of evaluating the function. If the result is an object, a vanilla object containing the serializable properties of the result is returned.
|
2022-07-05 13:41:43 +00:00
|
|
|
|
|
|
|
## Example 1
|
|
|
|
|
|
|
|
```ts
|
|
|
|
const executionContext = await page.mainFrame().executionContext();
|
|
|
|
const result = await executionContext.evaluate(() => Promise.resolve(8 * 7))* ;
|
|
|
|
console.log(result); // prints "56"
|
|
|
|
```
|
|
|
|
|
|
|
|
## Example 2
|
|
|
|
|
2022-08-11 09:45:35 +00:00
|
|
|
A string can also be passed in instead of a function:
|
2022-07-05 13:41:43 +00:00
|
|
|
|
|
|
|
```ts
|
|
|
|
console.log(await executionContext.evaluate('1 + 2')); // prints "3"
|
|
|
|
```
|
|
|
|
|
|
|
|
## Example 3
|
|
|
|
|
2022-08-11 09:45:35 +00:00
|
|
|
Handles can also be passed as `args`. They resolve to their referenced object:
|
2022-07-05 13:41:43 +00:00
|
|
|
|
|
|
|
```ts
|
|
|
|
const oneHandle = await executionContext.evaluateHandle(() => 1);
|
|
|
|
const twoHandle = await executionContext.evaluateHandle(() => 2);
|
|
|
|
const result = await executionContext.evaluate(
|
2022-08-11 09:45:35 +00:00
|
|
|
(a, b) => a + b,
|
|
|
|
oneHandle,
|
|
|
|
twoHandle
|
2022-07-05 13:41:43 +00:00
|
|
|
);
|
|
|
|
await oneHandle.dispose();
|
|
|
|
await twoHandle.dispose();
|
|
|
|
console.log(result); // prints '3'.
|
|
|
|
```
|