i am launching a non-headless browser with puppeteer and i would like to reuse the same browser instance across multiple execution (this saves me many time in debugging and development).
my approach was to try to connect to running browser. if it fails, then launch the browser.
const debuggingPort = 9222;
const launchBrowser = async() => {
const browser = await puppeteer.launch({
headless: false,
debuggingPort,
});
await browser.disconnect();
return browser;
};
const connectToBrowser = async() => {
const browserURL = `http://localhost:${debuggingPort}`;
const browser = await puppeteer.connect({browserURL});
return browser;
};
const getBrowser = async() => {
let browser;
try {
console.log("connecting to browser");
browser = await connectToBrowser();
console.log("connecting to browser suceeded");
} catch (_err) {
console.log("connecting to browser failed");
}
if (!browser) {
try {
console.log("launching browser");
browser = await launchBrowser();
console.log("launching browser succeeded");
} catch (_err) {
console.log("launching browser failed");
}
}
return browser;
}
(async () => {
const browser = await getBrowser();
const page = await browser.newPage();
})();
when i run the code above, i get the an error
Error: Protocol error: Connection closed.
and i cannot figure out what am i doing wrong and what is the right fix.
a solution by a concrete example would be awesome.