扩展新函数给window
2024-09-03 03:28:49
page.exposeFunction(name, puppeteerFunction)
name
<string> Name of the function on the window objectpuppeteerFunction
<function> Callback function which will be called in Puppeteer's context.- returns: <Promise>
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
.
If the puppeteerFunction
returns a Promise, it will be awaited.
NOTE Functions installed via
page.exposeFunction
survive navigations.
An example of adding an md5
function into the page:
const puppeteer = require('puppeteer');
const crypto = require('crypto'); puppeteer.launch().then(async browser => {
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();
});
An example of adding a window.readfile
function into the page:
const puppeteer = require('puppeteer');
const fs = require('fs'); puppeteer.launch().then(async browser => {
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();
});
最新文章
- SQL优化有偿服务
- CLR Table-Valued函数
- IAP 破解漏洞验证
- java字符串替换函数高效实现
- IOS文件存储小结
- Cocos2d-x程序Windows下VC中文乱码的解决(用MultiByteToWideChar进行转换,VC2010有非常厉害的execution_character_set)
- MapReduce中一次reduce方法的调用中key的值不断变化分析及源码解析
- js的基础要点
- 25.Linux-Nor Flash驱动(详解)
- python导入不同目录下模块的方法
- JAVA反射中的getFields()方法和getDeclaredFields ()方法的区别
- [翻译] 介绍EF Core
- enumerate() 函数
- Linux之vi编辑器
- Java多线程02(线程安全、线程同步、等待唤醒机制)
- ubuntu打开windows下txt文档乱码问题的解决
- BaseDAO使用
- 软件开发模式,DevOps
- 三种方式控制GPIO
- container_of使用小结