@@ -88,6 +88,49 @@ def find_text_rect(
8888 # Limit max_results to prevent performance issues
8989 max_results = min (max_results , 100 )
9090
91+ # CRITICAL: Wait for extension injection to complete (CSP-resistant architecture)
92+ # The new architecture loads injected_api.js asynchronously, so window.sentience
93+ # may not be immediately available after page load
94+ try :
95+ browser .page .wait_for_function (
96+ "typeof window.sentience !== 'undefined'" ,
97+ timeout = 5000 , # 5 second timeout
98+ )
99+ except Exception as e :
100+ # Gather diagnostics if wait fails
101+ try :
102+ diag = browser .page .evaluate (
103+ """() => ({
104+ sentience_defined: typeof window.sentience !== 'undefined',
105+ extension_id: document.documentElement.dataset.sentienceExtensionId || 'not set',
106+ url: window.location.href
107+ })"""
108+ )
109+ except Exception :
110+ diag = {"error" : "Could not gather diagnostics" }
111+
112+ raise RuntimeError (
113+ f"Sentience extension failed to inject window.sentience API. "
114+ f"Is the extension loaded? Diagnostics: { diag } "
115+ ) from e
116+
117+ # Verify findTextRect method exists (for older extension versions that don't have it)
118+ try :
119+ has_find_text_rect = browser .page .evaluate (
120+ "typeof window.sentience.findTextRect !== 'undefined'"
121+ )
122+ if not has_find_text_rect :
123+ raise RuntimeError (
124+ "window.sentience.findTextRect is not available. "
125+ "Please update the Sentience extension to the latest version."
126+ )
127+ except RuntimeError :
128+ raise
129+ except Exception as e :
130+ raise RuntimeError (
131+ f"Failed to verify findTextRect availability: { e } "
132+ ) from e
133+
91134 # Call the extension's findTextRect method
92135 result_dict = browser .page .evaluate (
93136 """
0 commit comments