Skip to content

Automate browser based workflows with AI

fix(SKY-12710): scope domUtils.js injection to avoid page global collisions (#7636)

Aaron Perez4a492b8c7117
diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.py
index 283e21086..f10aeaacb 100644
--- a/skyvern/webeye/scraper/scraper.py
+++ b/skyvern/webeye/scraper/scraper.py
@@ -9,7 +9,7 @@ from playwright._impl._errors import TimeoutError
from playwright.async_api import ElementHandle, Frame, Locator, Page
from skyvern.config import settings
-from skyvern.constants import DEFAULT_MAX_TOKENS, SKYVERN_DIR, SKYVERN_ID_ATTR
+from skyvern.constants import DEFAULT_MAX_TOKENS, SKYVERN_ID_ATTR
from skyvern.exceptions import (
FailedToTakeScreenshot,
NoElementFound,
@@ -34,7 +34,7 @@ from skyvern.webeye.scraper.scraped_page import (
ScrapeExcludeFunc,
json_to_html,
)
-from skyvern.webeye.utils.page import SkyvernFrame
+from skyvern.webeye.utils.page import SkyvernFrame, load_js_script
LOG = structlog.get_logger()
@@ -137,19 +137,6 @@ BASE64_INCLUDE_ATTRIBUTES = {
}
-def load_js_script() -> str:
- # TODO: Handle file location better. This is a hacky way to find the file location.
- path = f"{SKYVERN_DIR}/webeye/scraper/domUtils.js"
- try:
- # TODO: Implement TS of domUtils.js and use the complied JS file instead of the raw JS file.
- # This will allow our code to be type safe.
- with open(path) as f:
- return f.read()
- except FileNotFoundError as e:
- LOG.exception("Failed to load the JS script", path=path)
- raise e
-
-
JS_FUNCTION_DEFS = load_js_script()
diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.py
index 22b0c0a39..763403955 100644
--- a/skyvern/webeye/utils/page.py
+++ b/skyvern/webeye/utils/page.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import base64
import json
+import re
import time
import urllib.parse
from enum import StrEnum
@@ -66,6 +67,24 @@ async def build_open_tabs_context(
return "\n".join(lines)
+_JS_TOP_LEVEL_DECL_RE = re.compile(
+ r"^(?:async\s+function|function|class|let|const|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)",
+ re.MULTILINE,
+)
+
+
+def _wrap_js_in_isolated_scope(script: str) -> str:
+ # page.evaluate runs string scripts through a sloppy indirect eval, which hoists
+ # top-level declarations into the page's global scope and throws
+ # "Identifier 'X' has already been declared" when the site's own JS holds a global
+ # lexical binding with the same name. Scope the script in an IIFE and export via
+ # property writes, which never collide; typeof guards drop names the column-0 regex
+ # matched inside block comments.
+ names = sorted(set(_JS_TOP_LEVEL_DECL_RE.findall(script)))
+ exports = "\n".join(f'if (typeof {name} !== "undefined") globalThis.{name} = {name};' for name in names)
+ return f"(() => {{\n{script}\n{exports}\n}})();"
+
+
def load_js_script() -> str:
# TODO: Handle file location better. This is a hacky way to find the file location.
path = f"{SKYVERN_DIR}/webeye/scraper/domUtils.js"
@@ -73,7 +92,7 @@ def load_js_script() -> str:
# TODO: Implement TS of domUtils.js and use the complied JS file instead of the raw JS file.
# This will allow our code to be type safe.
with open(path, encoding="utf-8") as f:
- return f.read()
+ return _wrap_js_in_isolated_scope(f.read())
except FileNotFoundError as e:
LOG.exception("Failed to load the JS script", path=path)
raise e
diff --git a/tests/unit/test_dom_scrape_crash_guards.py b/tests/unit/test_dom_scrape_crash_guards.py
index 11e625ba3..72442d778 100644
--- a/tests/unit/test_dom_scrape_crash_guards.py
+++ b/tests/unit/test_dom_scrape_crash_guards.py
@@ -48,3 +48,18 @@ class TestDomScrapeCrashGuards:
timeout=30,
)
assert result.returncode == 0, f"Failed:\n{result.stdout}\n{result.stderr}"
+
+ def test_injection_scope_isolation(self, tmp_path):
+ from skyvern.webeye.utils.page import load_js_script
+
+ script = Path(__file__).parent / "test_domutils_injection_scope.js"
+ assert script.exists(), f"Missing {script}"
+ loaded_path = tmp_path / "loaded_domutils.js"
+ loaded_path.write_text(load_js_script(), encoding="utf-8")
+ result = subprocess.run(
+ [_NODE, str(script), str(_DOMUTILS), str(loaded_path)],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ assert result.returncode == 0, f"Failed:\n{result.stdout}\n{result.stderr}"
diff --git a/tests/unit/test_domutils_injection_scope.js b/tests/unit/test_domutils_injection_scope.js
new file mode 100644
index 000000000..0ea3030f3
--- /dev/null
+++ b/tests/unit/test_domutils_injection_scope.js
@@ -0,0 +1,123 @@
+// Behavioral test for domUtils.js injection scope isolation.
+//
+// page.evaluate runs string scripts through a sloppy indirect eval, which hoists
+// top-level declarations into the page's global scope. When the target site's own
+// JS holds a global lexical binding with the same name (e.g. `let uniqueId`),
+// that hoist throws "SyntaxError: Identifier 'uniqueId' has already been declared"
+// before any of our code runs. The loader must therefore ship domUtils.js wrapped
+// in an isolated scope that exports entry points via property writes instead.
+//
+// Usage: node test_domutils_injection_scope.js <raw domUtils.js> <load_js_script() output>
+
+const assert = require("node:assert");
+const fs = require("node:fs");
+const vm = require("node:vm");
+
+const [, , rawPath, wrappedPath] = process.argv;
+const rawScript = fs.readFileSync(rawPath, "utf8");
+const wrappedScript = fs.readFileSync(wrappedPath, "utf8");
+
+// Entry points invoked from Python snippets (handler.py, scraper.py, page.py,
+// browser_ops.py) or by the captcha extension — all must stay reachable as
+// globals after injection.
+const ENTRY_POINTS = [
+ "buildElementObject",
+ "buildElementsAndDrawBoundingBoxes",
+ "buildTreeFromBody",
+ "captchaSolvedCallback",
+ "getCaptchaSolves",
+ "getElementDomDepth",
+ "getHoverStylesMap",
+ "getIncrementElements",
+ "getScrollWidthAndHeight",
+ "getScrollXY",
+ "getSelectOptions",
+ "isAnimationFinished",
+ "isInteractable",
+ "isWindowScrollable",
+ "removeAllUniqueIds",
+ "removeBoundingBoxes",
+ "safeScrollToTop",
+ "scrollNearestScrollableContainer",
+ "scrollToElementBottom",
+ "scrollToElementTop",
+ "scrollToNextPage",
+ "scrollToXY",
+ "startGlobalIncrementalObserver",
+ "stopGlobalIncrementalObserver",
+ "uniqueId",
+];
+
+// Minimal browser surface touched by domUtils.js top-level statements.
+function makeContext() {
+ const sandbox = {
+ console,
+ MutationObserver: class {
+ observe() {}
+ disconnect() {}
+ },
+ };
+ vm.createContext(sandbox);
+ vm.runInContext("globalThis.window = globalThis;", sandbox);
+ // The page's own script: a classic script whose top-level `let` creates a
+ // persistent global lexical binding, exactly like a site-owned <script>.
+ vm.runInContext("let uniqueId = 1;", sandbox);
+ return sandbox;
+}
+
+// Mirrors Playwright's utilityScript `this.global.eval(expression)`.
+function indirectEval(sandbox, code) {
+ sandbox.__code = code;
+ try {
+ return vm.runInContext("(0, eval)(__code)", sandbox);
+ } finally {
+ delete sandbox.__code;
+ }
+}
+
+let failures = 0;
+function check(name, fn) {
+ try {
+ fn();
+ console.log(`ok - ${name}`);
+ } catch (err) {
+ failures += 1;
+ console.error(`FAIL - ${name}: ${err.message}`);
+ }
+}
+
+check("raw domUtils.js collides with a page-owned lexical uniqueId", () => {
+ assert.throws(
+ () => indirectEval(makeContext(), rawScript),
+ /already been declared/,
+ );
+});
+
+check("loaded script survives a page-owned lexical uniqueId", () => {
+ indirectEval(makeContext(), wrappedScript);
+});
+
+check("loaded script is re-injectable and exports all entry points", () => {
+ const ctx = makeContext();
+ indirectEval(ctx, wrappedScript);
+ const counterAfterFirstInjection = ctx.elementIdCounter;
+ assert.ok(
+ counterAfterFirstInjection,
+ "elementIdCounter should be initialized",
+ );
+ indirectEval(ctx, wrappedScript);
+ assert.strictEqual(
+ ctx.elementIdCounter,
+ counterAfterFirstInjection,
+ "re-injection must not reset elementIdCounter",
+ );
+ for (const name of ENTRY_POINTS) {
+ assert.strictEqual(
+ typeof ctx[name],
+ "function",
+ `${name} should be exported as a global function`,
+ );
+ }
+});
+
+process.exit(failures ? 1 : 0);