DEV Community

Omer Saleem
Omer Saleem

Posted on Originally published at omerbinsaleem.com

Whose Dialog Did Your Script Just Answer?

Originally published at omerbinsaleem.com by Omer Bin Saleem (Omer Saleem).

Attaching to a browser that other sessions share makes your script responsible for every tab in it, including the tabs you never opened.

How to do it

  1. Treat a shared browser as shared state. When you connect over CDP, you are not attached to one tab. You are attached to every tab in that browser, including the ones other sessions are driving right now.
  2. List the pages before you do any work. Enumerate the open pages first and mark the ones that are not yours, instead of finding out about them halfway through a run.
  3. Give every foreign page a no-op dialog handler. Playwright answers any JS dialog it sees on any page it is attached to, so attach p.on('dialog', () => {}) to each page you did not open. Their dialogs then stay with their owners.
  4. Only after that guard is in place, open your own page and do the work you came for.
  5. On exit, close your own page and nothing else. Never call browser.close() on a browser other sessions share. Their work is in those tabs.
  6. The cost of skipping the guard is small and confusing: one unguarded run crashed with "No dialog is showing" and left its own tab open behind it. The guard is one line per foreign page, written before the first click.

Prompt to copy

I have a Playwright script that connects over CDP to an already running browser. Other sessions are driving their own tabs in that same browser. Rewrite it so that, before it touches anything, it enumerates the existing pages and attaches a no-op dialog handler to every page it did not open, then opens and works in its own page. On exit it must close only its own page and never call browser.close(). Then point out every remaining place where the script acts on a tab it does not own.
Enter fullscreen mode Exit fullscreen mode

I am Omer Bin Saleem, a frontend chapter lead who builds with AI every day. One practical AI hack a day at omerbinsaleem.com. LinkedIn: omer-bin-saleem ยท Instagram: @iomerbinsaleem.

Written with AI assistance, from my own work notes.

Top comments (0)