Skip to main content
Version: 24.38.0

Page.exposeFunction() 方法

🌐 Page.exposeFunction() method

该方法在页面的 window 对象上添加了一个名为 name 的函数。调用该函数时,会在 node.js 中执行 puppeteerFunction,并返回一个 Promise,该 Promise 解析为 puppeteerFunction 的返回值。

🌐 The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in node.js and returns a Promise which resolves to the return value of puppeteerFunction.

如果 puppeteerFunction 返回一个 Promise,它将被等待。

🌐 If the puppeteerFunction returns a Promise, it will be awaited.

note

通过 page.exposeFunction 安装的函数在导航过程中能够保留。

🌐 Functions installed via page.exposeFunction survive navigations.

语法

🌐 Signature

class Page {
abstract exposeFunction(
name: string,
pptrFunction:
| Function
| {
default: Function;
},
): Promise<void>;
}

参数

🌐 Parameters

范围

🌐 Parameter

类型

🌐 Type

描述

🌐 Description

name

string

窗口对象上的函数名称

🌐 Name of the function on the window object

pptrFunction

Function | { default: Function; }

将在 Puppeteer 上下文中调用的回调函数。

🌐 Callback function which will be called in Puppeteer's context.

返回:

Promise<void>

示例 1

🌐 Example 1

在页面中添加 md5 函数的示例:

🌐 An example of adding an md5 function into the page:

import puppeteer from 'puppeteer';
import crypto from 'crypto';

const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('md5', text =>
crypto.createHash('md5').update(text).digest('hex'),
);
await page.evaluate(async () => {
// use window.md5 to compute hashes
const myString = 'PUPPETEER';
const myHash = await window.md5(myString);
console.log(`md5 of ${myString} is ${myHash}`);
});
await browser.close();

示例 2

🌐 Example 2

在页面中添加 window.readfile 函数的示例:

🌐 An example of adding a window.readfile function into the page:

import puppeteer from 'puppeteer';
import fs from 'node:fs';

const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('readfile', async filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, text) => {
if (err) reject(err);
else resolve(text);
});
});
});
await page.evaluate(async () => {
// use window.readfile to read contents of a file
const content = await window.readfile('/etc/hosts');
console.log(content);
});
await browser.close();