Skip to main content
Version: v2

Reconnect to an existing Browser

note

Looking for full developer docs? See them here. This feature is only available on the Enterprise plans.

Reconnecting to an existing browser is useful if you want to avoid logging in multiple times, or if you leave a process pending and want to open a websocket connection again once you're ready to resume automation, amongst other use cases.

If you want to reconnect to a browser, all you have to do is fetch the browser's websocket endpoint which you can reconnect with later. You do so by using a CDP connection to the browser and triggering the Browserless.reconnect CDP command, which will keep that browser alive and allow you to reconnect to it within the specified timeout. This virtually replaces thekeepalive flag that was previously used in V1.

Sample snippet

You can listen for captchas on the site, in puppeteer it would be like this:

import puppeteer from 'puppeteer-core';
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
const queryParams = new URLSearchParams({
token: "YOUR_API_KEY" ,
timeout: 60000,
}).toString();

// Recaptcha
(async() => {
const browser = await puppeteer.connect({
browserWSEndpoint: `wss://chrome.browserless.io/chromium?${queryParams}`,
});
const page = await browser.newPage();
const cdp = await page.createCDPSession();
await page.goto('https://www.example.com');

// Allow this browser to run for 1 minute, then shut down if nothing connects to it.
// Defaults to the overall timeout set on the instance, which is 5 minutes if not specified.
const { error, browserWSEndpoint } = await cdp.send('Browserless.reconnect', {
timeout: 60000,
});

if (error) throw error;
console.log(`${browserWSEndpoint}?${queryParams}`);

await browser.close();
//Reconnect using the browserWSEndpoint that was returned from the CDP command.
const browserReconnect = await puppeteer.connect({
browserWSEndpoint: `${browserWSEndpoint}?${queryParams}`,
});
const [pageReconnect] = await browserReconnect.pages();
await sleep(2000);
await pageReconnect.screenshot({
path: 'reconnected.png',
fullPage: true,
});
await browserReconnect.close();

})().catch((e) => {
console.error(e);
process.exit(1);
});