Playwright: repeatedly connect and disconnect to same browser and page instances using connectOverCDP

I have a environment where I need to have a browser and one page constantly open. I want to use Playwright to connect to it, do certain actions on the application, and stop the script. I might need to run several scripts against this browser and page instances. So it’s a no to new pages etc. – it needs to be this specific page and browser instance. So the first script could click on a button, the next could login etc.

Using Playwright, I can connect to the browser using connectOverCDP without any problems. I get the context and the page and can interact with the page. The first time I run any script, all works fine. But when I run a new script using the similar way to connect and get the page, I get an error about “Execution context was destroyed, most likely because of a navigation” or something similar. There is no way to gracefully disconnect from the connection.

I’ve tried several ways to disconnect from the connection: browser.close(), page.close(), context.close(). Without any of them, the scripts are left hanging. I can stop the script using process.exit(). But whatever I do, the next script is having issues or the page is actually closed – which is not what I need to do.

I have used Puppeteer to connect to the browser and after using browser.disconnect() all works fine on the next script call. But as Playwright is used in other projects, it makes sense to try to use the same thing in this case too.

So my question is, is there a way to do what I’m trying to do?

This is my current way to connect to the browser (localhost for dev purposes).

const browser = await playwright.chromium.connectOverCDP("http://localhost:9222");
const context = browser.contexts()[0];
const page = context.pages()[0];