Eric
Eric

Reputation: 5215

How can I pass an existing object into Puppeteer's page.evaluate?

I'm using a nice logging library in node, which writes a log message with a simple logger.debug("Message") method.

I can't figure out how to pass the logger object into page.evaluate so I can use it in there.

I explored page.exposeFunction but that seems to be for an anonymous function that is created inline. I want to pass the existing logger object that I already have instantiated.

I also tried just adding the whole thing as to the page object, i.e. page.logger = logger, but no luck.

What can I do?

Upvotes: 2

Views: 515

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13782

You can try some variants.

  1. If logger.debug() does not need logger as its this, this may suffice:
await page.exposeFunction('loggerDebug', logger.debug);
  1. If logger.debug() needs logger as its this, this may suffice:
await page.exposeFunction('loggerDebug', logger.debug.bind(logger));
  1. And you can try a wrapper:
await page.exposeFunction('loggerDebug', (msg) => { logger.debug(msg); });

All variants can be used via:

await page.evaluate(async () => {
  // ...
  window.loggerDebug("Message");
  // ...
});

Upvotes: 4

Related Questions