Is it possible to close a Puppeteer Browser using its contextId?

Viewed 1601

This is an update to a question I had asked previously but wasn't thinking straight when I asked the question (I was taking a very backwards approach to my solution). I'm currently working with Puppeteer and I'm trying to create an association between a particular task and a puppeteer browser instance. Right now I am currently getting the browser's context id using:

const {browserContextId} = await browser._connection.send('Target.createBrowserContext');

and I am storing it in a file along with other details related to the task. My goal is to somehow be able to close that browser instance using the stored context id. I've given this issue a read on the Puppeteer's GitHub hoping that it would help in some way but it seems that it's not super helpful to me as its not really related to what I'm doing.

The real issue is that I am going to be spawning browser instances in one file and attempting to close them in another, otherwise this wouldn't be an issue at all. Right now the only thing I've been able to do is just spawn another browser instance using the context id (pretty much useless for my task) and have had no luck in closing it or disposing it.

Any help would be greatly appreciated, thanks!

P.S. If there is a better approach to solving this association issue I'm all ears!

1 Answers

Turns out I was thinking about it way too much and trying to make it too complex. For anyone trying to do something similar I'll leave my solution here for you.

Instead of using the browser's context id I found it much easier to just grab the browser's process id (pid). From there I could kill the process using different strategies based on where I was running the close command.

For Node.js:

// Lets say for example we're instantiating our browser like this
const browser = await puppeteer.launch({ headless: false });

// You can simply run this to get the browser's pid
const browserPID = browser.process().pid

// Then you can either store it for use later
fs.writeFile(file, JSON.stringify(jsondata, null, 4), (err) => {
    if (err) console.log(err);
})

// Or just kill the process
process.kill(browserPID);

Keep in mind that if you are storing the PID you need to read the file and parse the data to pass into the process.kill command.

For React via Electron

// Require process from the electron file
const process = window.require('process');

// Then same process as before
process.kill(yourbrowserPID);

Hopefully my stupidity can help someone in the future if they are trying to do something similar. It was way easier than I was making it out to be.

Related