8000 feat(browser): document evaluate_js execution context (no top-level await/return) or wrap in async IIFE · Issue #2 · Mnehmos/mnehmos.ooda.mcp · GitHub
[go: up one dir, main page]

Skip to content

feat(browser): document evaluate_js execution context (no top-level await/return) or wrap in async IIFE #2

Open

Description

@Mnehmos

Summary

evaluate_js runs the supplied script in a bare function scope that is not async and not a module. This isn't documented, so the natural first attempt (use await, end with return) fails, and you only learn the rules by trial and error.

Observed

Two distinct failures hit during normal use:

// 1) top-level await
await new Promise(r => setTimeout(r, 300));
// -> SyntaxError: await is only valid in async functions and the top level bodies of modules

// 2) return statement
return JSON.stringify(result);
// -> SyntaxError: Illegal return statement

The working pattern turned out to be: no await, no return — just end with a bare expression whose value becomes the result:

const x = document.querySelector('.foo').getBoundingClientRect();
JSON.stringify({ w: x.width }); // last expression is the return value

Why it matters

Anything involving timing (document.fonts.load(...), waiting for an async render) or the natural return value idiom fails on first try. A small but repeated papercut.

Suggested fix (either is fine)

  1. Wrap the script in an async IIFE before eval so await/return both work:
    const result = await page.evaluate(`(async () => { ${script} })()`);
  2. Or document the constraint in the tool description: "Script runs in a non-async function scope. No top-level await; no return — the value of the final expression is returned."

Option 1 is the better DX — it removes the footgun entirely.

Environment

  • Engine: Playwright, headless
  • Surfaced while driving a Vite/React app for visual verification.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0