Puppeteer 中文文档v25.8.0

Page.exposeFunction() 方法

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

如果 puppeteerFunction 返回 Promise,该 Promise 将被 await。

ℹ️注意

通过 page.exposeFunction 安装的函数在导航后仍然存在。

签名

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

参数

参数

类型

说明

name

string

window 对象上函数的名称

pptrFunction

Function | { default: Function; }

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

返回值:

Promise<void>

示例 1

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

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

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

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();