Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

javascript - Custom event is not a function, Puppeteer

I am unable to execute a custom event using Puppeteer.

This is how my code looks like but it doesn't seem to be working.

const browser = await puppeteer.launch({
    defaultViewport: { width: 1920, height: 1080 },
    headless: false,
  });

  const page = await browser.newPage();

  await page.exposeFunction('getInfo', (event) => {
    console.log('getInfo');
  });

await page.goto('url');

  await page.evaluate(() => {
    window.document.getInfo(); // TypeError: window.document.getInfo is not a function
  });

what am I doing wrong?

question from:https://stackoverflow.com/questions/65916680/custom-event-is-not-a-function-puppeteer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation says:

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.

the key part is "on the page's window object". You're trying to find the function in window.document object.

This code should fix your problem:

await page.evaluate(() => {
    window.getInfo();
});

Also be aware that any such function returns a Promise, so you might want to do:

await page.evaluate(async () => {
    await window.getInfo();
});

if your function should e.g. return something you want to later use inside page.evaluate() callback function.

See the documentation for Puppeteer API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...