Improve Test Stablity(1) - close popup and wait for cleanups
Issue You click an openPopup button inside an iframe. A new popup window appears, you input data and click the close button inside the popup. After 20+ repeated cycles, the popup no longer opens. Errors appear: context / Target closed
Problem Description(What is lost context / Target closed?)
The issue you’re experiencing — popup windows stop opening after 20+ repeated clicks, and you
see "lost context" / "Target closed" errors — is the most typical resource leak / context
invalidation issue when automating pages with iframes + popups in Playwright.
2. Meaning of the Errors
lost context: The browser has destroyed the page / iframe / popup window you were trying to
interact with.
Target closed: The browser context was recycled, timed out, or exhausted from too many repeated
creations without proper cleanup.
3. Root Cause Summary
The error only appears after 20+ consecutive operations — this is classic resource leakage.
The root cause is:Popup window contexts are NOT being fully released/cleaned up by the browser
after closing, and cached iframe handles become stale over time.
Eventually, the browser runs out of available contexts → new popups can no longer open →
automation fails.
Solution
// Short wait for browser internal async cleanup (Playwright can't detect this) // 1. Iframe back to interactive state // 2. Popup renderer process destroyed // 3. JS event loop idle // 4. Prevent context overload await expect.poll(() => popupPage.isClosed()).toBe(true); await page.waitForTimeout(300);Why we need a short wait (300ms) ?
Even after we assert popupPage.isClosed() === true,the browser still has background async cleanup work that Playwright cannot detect or wait for automatically.
The 300ms wait is NOT for the popup to close,it’s for the browser’s internal async cleanup to finish:
- Wait for the iframe to return to an interactive/clickable state
- Wait for the browser to fully destroy the popup’s renderer process
- Wait for the JavaScript event loop to become idle
- Prevent rapid repeated actions from overloading the browser context/li>
These four steps happen asynchronously in the browser background,and Playwright has no visibility into whether they are fully complete.
If you immediately click openPopup again before these cleanups finish,the iframe may ignore the click, the new popup will not open,and you will get context lost / target closed errors. This is why after 20+ rapid loops, the failure appears —one small incomplete cleanup is enough to break the whole flow.