2

如此处所示,Puppeteer 允许覆盖 Javascript 函数。我想覆盖 showOpenFilePicker 函数。也就是当showOpenFilePicker 被网页调用时。我想在 showOpenFilePicker 之前运行另一个函数。

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  await page.evaluateOnNewDocument(() => {
    Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", {
      value: () => {
        console.log("Hey there");
      },
    });
  });

  await page.goto("https://example.com");

  await page.evaluate(() => {
    console.log(HTMLCanvasElement.prototype.toBlob.toString());
  });

  // await browser.close();
})();

4

1 回答 1

0

您可以覆盖 Puppeteer 中的内置函数,如下面的代码示例所示。这会将原始函数替换为将参数记录到控制台的覆盖。

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  await page.evaluateOnNewDocument(() => {
    const originalShowOpenFilePicker = window.showOpenFilePicker;
    window.showOpenFilePicker = (...args) => {
      console.log('Modified `showOpenFilePicker` called with these arguments:', args);
      return originalShowOpenFilePicker(...args);
    };
  });

  await page.goto("https://example.com");

  await page.evaluate(() => {
    console.log(showOpenFilePicker());
  });

  // await browser.close();
})();
于 2021-02-23T14:13:49.087 回答