Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 25 additions & 19 deletions stagehand/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import time
from typing import Optional, Union

from playwright._impl._errors import TargetClosedError
from playwright.async_api import CDPSession, Page
from pydantic import BaseModel

Expand Down Expand Up @@ -53,28 +54,33 @@ def update_root_frame_id(self, new_id: str):
self._frame_id = new_id
self._stagehand.logger.debug(f"Updated frame ID to {new_id}", category="page")

# TODO try catch here
async def ensure_injection(self):
"""Ensure custom injection scripts are present on the page using domScripts.js."""
exists_before = await self._page.evaluate(
"typeof window.getScrollableElementXpaths === 'function'"
)
if not exists_before:
global _INJECTION_SCRIPT
if _INJECTION_SCRIPT is None:
import os
try:
exists_before = await self._page.evaluate(
"typeof window.getScrollableElementXpaths === 'function'"
)
if not exists_before:
global _INJECTION_SCRIPT
if _INJECTION_SCRIPT is None:
import os

script_path = os.path.join(os.path.dirname(__file__), "domScripts.js")
try:
with open(script_path) as f:
_INJECTION_SCRIPT = f.read()
except Exception as e:
self._stagehand.logger.error(f"Error reading domScripts.js: {e}")
_INJECTION_SCRIPT = "/* fallback injection script */"
# Inject the script into the current page context
await self._page.evaluate(_INJECTION_SCRIPT)
# Ensure that the script is injected on future navigations
await self._page.add_init_script(_INJECTION_SCRIPT)
script_path = os.path.join(os.path.dirname(__file__), "domScripts.js")
try:
with open(script_path) as f:
_INJECTION_SCRIPT = f.read()
except Exception as e:
self._stagehand.logger.error(f"Error reading domScripts.js: {e}")
_INJECTION_SCRIPT = "/* fallback injection script */"
# Inject the script into the current page context
await self._page.evaluate(_INJECTION_SCRIPT)
# Ensure that the script is injected on future navigations
await self._page.add_init_script(_INJECTION_SCRIPT)
except TargetClosedError as e:
Copy link

@cubic-dev-ai cubic-dev-ai bot Feb 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Catching only TargetClosedError drops the previous handling of "Execution context was destroyed" errors, which are a different Playwright exception type (playwright._impl._errors.Error). Both errors occur during page navigation and should be caught. This is a regression — the original navigation error will now bubble up unhandled.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At stagehand/page.py, line 79:

<comment>Catching only `TargetClosedError` drops the previous handling of `"Execution context was destroyed"` errors, which are a different Playwright exception type (`playwright._impl._errors.Error`). Both errors occur during page navigation and should be caught. This is a regression — the original navigation error will now bubble up unhandled.</comment>

<file context>
@@ -75,14 +76,11 @@ async def ensure_injection(self):
-                )
-            else:
-                raise
+        except TargetClosedError as e:
+            self._stagehand.logger.warning(
+                f"ensure_injection failed (page may be navigating): {e}",
</file context>
Fix with Cubic

self._stagehand.logger.warning(
f"ensure_injection failed (page may be navigating): {e}",
category="page",
)

async def goto(
self,
Expand Down