waitForSelector fails with "Inspected target navigated or closed" when the click-triggered navigation commits after the wait is issued
Summary
page.waitForSelector() fails with -32000 Inspected target navigated or closed when the navigation triggered by the preceding locator.click() commits after the wait has been issued. The wait is one Runtime.evaluate (awaitPromise: true) pinned to the execution context that was current when it was sent; the commit destroys that context and Chrome rejects the pending evaluate. Frame.evaluate retries only Cannot find context with specified id (the case from #1778), so the error surfaces to the caller.
Reproduced with @browserbasehq/[email protected] against Chrome 153 (--headless=new, connected over cdpUrl). main carries the same code (packages/extension/understudy/page.ts waitForSelector, packages/extension/understudy/frame.ts retry filter), so I expect the extension runtime to behave the same.
Repro
Standalone script, no LLM needed. A local server answers the form submission after a short delay (a real server does this naturally; 100 ms makes it deterministic, and even 0 ms fails about 2 runs in 5 here).
// node repro.mjs ws://127.0.0.1:9222/devtools/browser/<id> [delayMs=100]
import http from "node:http";
import { Stagehand } from "@browserbasehq/stagehand";
const cdpUrl = process.argv[2];
const delayMs = Number(process.argv[3] ?? 100);
const server = http.createServer((req, res) => {
if (req.url.startsWith("/submit")) {
setTimeout(() => {
res.setHeader("Content-Type", "text/html");
res.end(`<html><body><p id="query">${req.url}</p></body></html>`);
}, delayMs);
return;
}
res.setHeader("Content-Type", "text/html");
res.end(`<html><body><form action="/submit"><input id="name" name="name"><button id="submit">Go</button></form></body></html>`);
});
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const base = `http://127.0.0.1:${server.address().port}`;
const stagehand = new Stagehand({ env: "LOCAL", localBrowserLaunchOptions: { cdpUrl }, verbose: 0 });
await stagehand.init();
const page = await stagehand.context.newPage();
try {
await page.goto(`${base}/form.html`);
await page.locator("#name").fill("panda");
await page.locator("#submit").click();
await page.waitForSelector("#query", { timeout: 5000 });
console.log("OK:", await page.locator("#query").textContent());
} catch (e) {
console.log("FAIL:", e.message);
} finally {
await stagehand.close().catch(() => {});
server.close();
}$ google-chrome --headless=new --remote-debugging-port=9222 about:blank &
$ node repro.mjs "$(curl -s localhost:9222/json/version | jq -r .webSocketDebuggerUrl)" 100
FAIL: -32000 Inspected target navigated or closed
$ node repro.mjs "$(curl -s localhost:9222/json/version | jq -r .webSocketDebuggerUrl)" 0
OK: /submit?name=panda # or FAIL, depending on a few msWhat the protocol trace shows
After the Input.dispatchMouseEvent burst returns, the SDK sends Runtime.enable and then the waitForSelector Runtime.evaluate with contextId of the form page. Meanwhile the form submission navigates: Page.frameScheduledNavigation → Network.responseReceived → Runtime.executionContextsCleared → Page.frameNavigated → Runtime.executionContextCreated. If the evaluate is accepted before executionContextsCleared, Chrome later answers it with Inspected target navigated or closed (other browsers word it Execution context was destroyed). If it arrives after, ExecutionContextRegistry has been wiped and waitForMainWorld picks up the new context, which is why the outcome flips on latency.
Expected
waitForSelector is idempotent, so it can re-issue the wait against the new main world with the remaining timeout when the pending evaluate is killed by a navigation. This should stay scoped to the wait (and similar idempotent waits), not to Frame.evaluate in general, since replaying an arbitrary evaluate can duplicate side effects (as noted in #2751).
I have a small patch for this and can open a PR against main with a v3 backport if that is welcome.
Environment
@browserbasehq/stagehand3.7.3 (also read the same code onmainat 4.1.0)- Chrome 153.0.0.0 headless, Linux x86_64, Node 26
Source: browserbase/stagehand