Page.exposeFunction() 方法
此方法會在頁面的 window
物件上新增一個名為 name
的函式。當呼叫此函式時,它會在 node.js 中執行 puppeteerFunction
,並傳回一個 Promise
,該 Promise
會解析為 puppeteerFunction
的傳回值。
如果 puppeteerFunction 傳回一個 Promise
,它將會被等待。
注意
透過 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';
(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();
})();