|
2 | 2 | import time |
3 | 3 | from typing import Optional, Union |
4 | 4 |
|
| 5 | +from playwright._impl._errors import TargetClosedError |
5 | 6 | from playwright.async_api import CDPSession, Page |
6 | 7 | from pydantic import BaseModel |
7 | 8 |
|
@@ -53,28 +54,33 @@ def update_root_frame_id(self, new_id: str): |
53 | 54 | self._frame_id = new_id |
54 | 55 | self._stagehand.logger.debug(f"Updated frame ID to {new_id}", category="page") |
55 | 56 |
|
56 | | - # TODO try catch here |
57 | 57 | async def ensure_injection(self): |
58 | 58 | """Ensure custom injection scripts are present on the page using domScripts.js.""" |
59 | | - exists_before = await self._page.evaluate( |
60 | | - "typeof window.getScrollableElementXpaths === 'function'" |
61 | | - ) |
62 | | - if not exists_before: |
63 | | - global _INJECTION_SCRIPT |
64 | | - if _INJECTION_SCRIPT is None: |
65 | | - import os |
| 59 | + try: |
| 60 | + exists_before = await self._page.evaluate( |
| 61 | + "typeof window.getScrollableElementXpaths === 'function'" |
| 62 | + ) |
| 63 | + if not exists_before: |
| 64 | + global _INJECTION_SCRIPT |
| 65 | + if _INJECTION_SCRIPT is None: |
| 66 | + import os |
66 | 67 |
|
67 | | - script_path = os.path.join(os.path.dirname(__file__), "domScripts.js") |
68 | | - try: |
69 | | - with open(script_path) as f: |
70 | | - _INJECTION_SCRIPT = f.read() |
71 | | - except Exception as e: |
72 | | - self._stagehand.logger.error(f"Error reading domScripts.js: {e}") |
73 | | - _INJECTION_SCRIPT = "/* fallback injection script */" |
74 | | - # Inject the script into the current page context |
75 | | - await self._page.evaluate(_INJECTION_SCRIPT) |
76 | | - # Ensure that the script is injected on future navigations |
77 | | - await self._page.add_init_script(_INJECTION_SCRIPT) |
| 68 | + script_path = os.path.join(os.path.dirname(__file__), "domScripts.js") |
| 69 | + try: |
| 70 | + with open(script_path) as f: |
| 71 | + _INJECTION_SCRIPT = f.read() |
| 72 | + except Exception as e: |
| 73 | + self._stagehand.logger.error(f"Error reading domScripts.js: {e}") |
| 74 | + _INJECTION_SCRIPT = "/* fallback injection script */" |
| 75 | + # Inject the script into the current page context |
| 76 | + await self._page.evaluate(_INJECTION_SCRIPT) |
| 77 | + # Ensure that the script is injected on future navigations |
| 78 | + await self._page.add_init_script(_INJECTION_SCRIPT) |
| 79 | + except TargetClosedError as e: |
| 80 | + self._stagehand.logger.warning( |
| 81 | + f"ensure_injection failed (page may be navigating): {e}", |
| 82 | + category="page", |
| 83 | + ) |
78 | 84 |
|
79 | 85 | async def goto( |
80 | 86 | self, |
|
0 commit comments