page.exposeFunction(name, puppeteerFunction)

  • name <string> Name of the function on the window object
  • puppeteerFunction <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();
});
 

最新文章

  1. SQL优化有偿服务
  2. CLR Table-Valued函数
  3. IAP 破解漏洞验证
  4. java字符串替换函数高效实现
  5. IOS文件存储小结
  6. Cocos2d-x程序Windows下VC中文乱码的解决(用MultiByteToWideChar进行转换,VC2010有非常厉害的execution_character_set)
  7. MapReduce中一次reduce方法的调用中key的值不断变化分析及源码解析
  8. js的基础要点
  9. 25.Linux-Nor Flash驱动(详解)
  10. python导入不同目录下模块的方法
  11. JAVA反射中的getFields()方法和getDeclaredFields ()方法的区别
  12. [翻译] 介绍EF Core
  13. enumerate() 函数
  14. Linux之vi编辑器
  15. Java多线程02(线程安全、线程同步、等待唤醒机制)
  16. ubuntu打开windows下txt文档乱码问题的解决
  17. BaseDAO使用
  18. 软件开发模式,DevOps
  19. 三种方式控制GPIO
  20. container_of使用小结

热门文章

  1. Nexus-vPC基础实验
  2. IDEA 查看字节码
  3. Java IO流详解(二)——File类
  4. 自定义配置 const
  5. dp求解各种子串子序列
  6. iOS 增强程序健壮性 - - 使用 NullSafe 对 &lt;null&gt; 处理
  7. CSS三列自适应布局(两边宽度固定,中间自适应)
  8. MySQL报Too many connections
  9. 使用win32com操作woord的方法记录
  10. Mybatis plus 插入数据时将自动递增的主键手动进行赋值设置