- 1 year ago
Puppeteer opening chrome instance for each file at once
By default, Puppeteer launches a new instance of Chrome for each new Puppeteer page you create. If you are opening multiple files with Puppeteer and don't want a separate Chrome instance for each file, you can reuse the same Chrome instance by using a single Puppeteer browser object and creating new pages within that browser.
Here's an example of how you can open multiple files using Puppeteer while reusing the same Chrome instance:
javascriptconst puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({ headless: false }); // You can set headless: true to run in headless mode
const page = await browser.newPage();
try {
const files = ['file1.html', 'file2.html', 'file3.html'];
for (const file of files) {
await page.goto(`file://${file}`);
// Do your processing on the page here
// For example: await page.screenshot({ path: `screenshot-${file}.png` });
}
} catch (err) {
console.error('Error:', err);
} finally {
await browser.close();
}
})();
In this example, we launch Puppeteer once and create a single browser instance. Then, we loop through the files
array and open each file in the page
using page.goto()
. You can perform any processing you need on each page inside the loop.
Remember to handle any errors and close the browser after you are done processing the files.
This way, you'll only have one instance of Chrome running, and Puppeteer will open each file in the same Chrome instance one by one.