Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer trigger function in node to run from browser event

I would like to trigger a function that runs in node from the browser. How can I do this?

  let log = () => console.log("helsadfl");

  await page.evaluate((log) => {
    document.addEventListener("click", function () {
      console.log(log);
    });
  }, log);

Additional: Why is this not able to console.log the target?

  await page.exposeFunction("log", (e) => console.log(e.target));

  await page.evaluate(() => {
    document.addEventListener("click", log);
  });

1 Answers

Try page.exposeFunction():

await page.exposeFunction('log', () => console.log("helsadfl"));

await page.evaluate(() => {
  document.addEventListener("click", async () => {
    await window.log();
  });
});
like image 57
vsemozhebuty Avatar answered May 18 '26 14:05

vsemozhebuty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!