zoukankan      html  css  js  c++  java
  • 扩展新函数给window

    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();
    });
    
     
  • 相关阅读:
    使用js方法时,调用的方法名明明一致,但就是不管用,解决
    最近ssh遇到异常及解决
    oracle中number数据类型简单明了解释
    Struts2 使用Jquery+ajax 文件上传
    PHP学习记录(二)
    PHP学习记录(一)
    Win7下Git SSH 创建Key
    webapck基础随手记
    分享一份JS前端面试题
    Redux零碎知识点回顾
  • 原文地址:https://www.cnblogs.com/justart/p/9747724.html
Copyright © 2011-2022 走看看