t97
t97

Reputation: 69

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?

Upvotes: 0

Views: 484

Answers (1)

pavelsaman
pavelsaman

Reputation: 8322

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.

Upvotes: 1

Related Questions