browser-use/browser-use · error · ValueError
JavaScript code is empty after cleaning
Error message
JavaScript code is empty after cleaning
What it means
Raised by _fix_javascript_string when, after stripping whitespace, removing wrapper quotes, and un-escaping quotes, the resulting JavaScript string is empty. It is a guard so an empty expression is never sent to CDP.
Source
Thrown at browser_use/actor/page.py:188
if (js_code.startswith('"') and js_code.endswith('"')) or (js_code.startswith("'") and js_code.endswith("'")):
# Check if it's a wrapped string (not part of JS syntax)
inner = js_code[1:-1]
if inner.count('"') + inner.count("'") == 0 or '() =>' in inner:
js_code = inner
# 2. Only fix clearly escaped quotes that shouldn't be
# But be very conservative - only if we're sure it's a Python string artifact
if '\\"' in js_code and js_code.count('\\"') > js_code.count('"'):
js_code = js_code.replace('\\"', '"')
if "\\'" in js_code and js_code.count("\\'") > js_code.count("'"):
js_code = js_code.replace("\\'", "'")
# 3. Basic whitespace normalization only
js_code = js_code.strip()
# Final validation - ensure it's not empty
if not js_code:
raise ValueError('JavaScript code is empty after cleaning')
return js_code
async def screenshot(self, format: str = 'png', quality: int | None = None) -> str:
"""Take a screenshot and return base64 encoded image.
Args:
format: Image format ('jpeg', 'png', 'webp')
quality: Quality 0-100 for JPEG format
Returns:
Base64-encoded image data
"""
session_id = await self._ensure_session()
params: 'CaptureScreenshotParameters' = {'format': format}
if quality is not None and format.lower() == 'jpeg':View on GitHub (pinned to 6c73fced2f)
Solutions
- Check the value before calling: if not js.strip(): raise/skip
- Log the raw page_function at the call site to find where it became empty
- If the code comes from an LLM action, add a non-empty constraint to the tool prompt
Example fix
# before
await page.evaluate(js_code) # js_code may be ''
# after
if not js_code or not js_code.strip():
raise ValueError('evaluate called with empty script')
await page.evaluate(js_code) Defensive patterns
Strategy: validation
Validate before calling
if not isinstance(js, str) or not js.strip():
raise ValueError('refusing to evaluate empty script') Type guard
def is_nonempty_script(js) -> bool:
return isinstance(js, str) and len(js.strip()) > 0 Try / catch
null
Prevention
- Never pass unvalidated LLM-generated code straight to evaluate
- Treat empty evaluate payloads as a caller bug, not a runtime condition
When it happens
Trigger: Passing an empty string or whitespace-only string to page.evaluate; passing a string that is only a pair of quotes ('""' or "''"), which the quote-unwrapping step strips to nothing; passing a variable that is None-ish or was truncated to empty by upstream code.
Common situations: LLM tool call produces an evaluate action with empty code; f-string interpolation that evaluates to empty (f'({expr})' with expr=''); copying a placeholder from docs without filling in the body.
Related errors
- JavaScript code must start with (...args) => format. Got: {p
- module '{__name__}' has no attribute '{name}'
- Failed to find DOM element based on backendNodeId, maybe pag
- Failed to click element: {js_e}
- JavaScript evaluation failed: {result["exceptionDetails"]}
AI-assisted analysis of browser-use/browser-use@6c73fced2f (2026-08-14).
Data as JSON: /api/errors/d0521fa710001671.
Report an issue: GitHub.