marko-36
marko-36

Reputation: 1486

Reuse a puppeteer instance (created by another module, Node.js)

The following Q&A's are related, but don't quite answer my question:

Also, it seems to me that this topic goes beyond this specific use case, probably a thing of Node itself, so I will be happy for links to a broader explanation.

Anyway: My Node app uses a module, which uses Puppeteer. I can supply launch params to it, but cannot access it later (or at least don't know how, or if even possible). This obviously runs it, creates a new page, and does its thing. Then I need to use Puppeteer directly, to render specific HTML given to it. Now, I could puppeteer.launch() and browser.newPage(), but this would create another Puppeteer instance (..right?). How can use/access the instance created by the mentioned module? Or, is there a way to create a single Pup instance and have other code use it by default, perhaps?

Upvotes: 1

Views: 754

Answers (2)

Darkosphere
Darkosphere

Reputation: 161

This is something related to export / import.

In the module where you launch your browser instance you should export the variable that holds that browser object, so you could import it in another file before reusing it.

Check the "Using export from" section at the end of the examples => export - Javascript | MDN
for some hint on how to do that.

Anyways if the module is not one of yourself it will be harder to do as you will need to figure out how this browser instance is used and disposed inside that specific module.

If you can figure that out and if the module that you use exports an object you may just add a method to that object to return it's browser instance.

If the module that you use appears to close the browser instance and relaunch it at times it may be easier to not bother trying to retrieve that browser instance from it and simply import puppeteer to launch a browser instance on which you will have full controll whithout the risk of crashing the other module or your app.

Upvotes: 0

marko-36
marko-36

Reputation: 1486

Ok,so trying further to answer my question I traversed through variables of the module which spawns puppeteer. In my case, we this is whatsapp-web.js. When the client is initialize()d, waclient.pupBrowser._connection._url is the value to pass to browserWSEndpoint parameter of puppeteer.connect(options). The browser then can be const browser = await pup.connect({browserWSEndpoint: waBrowserURL});. Also, const pup = require('puppeteer') is necessary.

Or better, I can just directly use waclient.pupBrowser, which is the browser instance created by whatsapp-web.js.

So, while this does solve my case, I am not sure how to proceed in scenarios, where the browser is not exposed/accessible as described above.

Upvotes: 1

Related Questions