playwright locator.click target closed: how to fix
Fixes Playwright 'Target closed' errors when the page or context closes mid-action. Use when clicks or fills fail because the target closed. Not for strict-mode violations.
TL;DR
The page, context, or browser closed while Playwright was acting on it. Usually the app navigated or the test closed the context too early. Keep the context alive for the whole test and await navigations before interacting.
Error
Error: locator.click: Target closedSteps
- Check whether the test closes the context or browser before the click (a misplaced
await context.close()or anafterEachthat runs early). Expected: you find the premature close. - If the app navigates on the previous action, await it:
await Promise.all([page.waitForNavigation(), page.getByRole('button', { name: 'Save' }).click()]). Expected: the click completes before navigation tears the page down. - If a popup or new tab opens, capture it explicitly:
const popup = await page.waitForEvent('popup'). Expected: actions target the right page object. - Avoid sharing one context across tests that close pages independently; prefer
test.usefixtures or new contexts per test. Expected: no cross-test teardown races. - Re-run the single test file. Expected: green without the target-closed error.
When to use
- The error is
Target closedon click, fill, or selectOption. - It happens after navigations, popups, or downloads.
When not to use
Strict mode violation(selector matched multiple elements).- The browser crashes entirely (check
browser has been closed).
Tool compatibility
- Playwright 1.30 through latest; all browsers.
Variant phrasings
locator.fill: Target closed
Same cause on fill; the page went away mid-action.
Page closed errors in Playwright
The general family; check who closed what and when.
Why it happens
Playwright drives a live page. If the page object is destroyed (navigation, close, crash) between locating and acting, the action has no target.
Edge cases
- Downloads trigger a navigation-like event in some apps; handle the download event before continuing.
page.close()in afinallyblock can race the last assertion; close inafterEachinstead.- Headed mode keeps pages alive longer, hiding the race that headless exposes.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_XwxJDVuEvsk35T8gA1y4lg
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.