本文へスキップ
バージョン: 22.5.0

Page.exposeFunction() メソッド

このメソッドは、ページの `window` オブジェクトに `name` という名前の関数を追加します。この関数が呼び出されると、Node.js で `puppeteerFunction` が実行され、`puppeteerFunction` の戻り値を解決する `Promise` を返します。

puppeteerFunction が `Promise` を返す場合、それは await されます。

注記

page.exposeFunction を介してインストールされた関数は、ページ遷移後も存続します。

注記

シグネチャ:

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

パラメータ

パラメータ説明
namestringwindow オブジェクト上の関数の名前
pptrFunctionFunction | { default: Function; }Puppeteer のコンテキストで呼び出されるコールバック関数。

戻り値

Promise<void>

例 1

ページに `md5` 関数を追加する例

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

(async () => {
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 'fs';

(async () => {
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();
})();