All Products
Search
Document Center

Function Compute:Use Browser Use Sandbox

Last Updated:Sep 01, 2026

Browser Use Sandbox is designed for Agents that need to open web pages, click buttons, fill forms, archive screenshots, or scrape dynamic pages. We recommend creating sandboxes from the browser template: port 3000 provides the browser service and can be connected through CDP by Puppeteer, Playwright, or BrowserUse.

If the task only needs web access, clicks, screenshots, downloads, and lightweight result extraction, use Browser Use Sandbox. If browser artifacts need to be processed in the same session by Python or Node.js for data cleanup, spreadsheet analysis, or report generation, use AIO Sandbox.

Use Cases

ScenarioDescription
Web data collectionOpen dynamic pages and extract titles, text, tables, links, or business fields.
Operations console automationLog in to consoles, fill forms, click buttons, download reports, or archive screenshots.
Page inspectionOpen pages on a schedule and verify key elements, screenshots, performance, or availability.
Lightweight E2E testingRun end-to-end tests in an isolated browser environment without polluting CI workers.
Browser tool AgentsLet an Agent complete multi-step web tasks through BrowserUse or similar frameworks.

Recommended Workflow

  1. Build a business template from the browser template, such as my-browser-template.

  2. Create a sandbox from the template and set a reasonable timeout.

  3. Get the public browser service host with sandbox.get_host(3000).

  4. Poll /health until the browser service is ready.

  5. Connect Puppeteer, Playwright, or BrowserUse through wss://<sandbox-host>/ws/automation.

  6. Open pages, click, type, take screenshots, generate PDFs, or download files.

  7. Save structured results, screenshots, HTML, PDFs, or downloaded files to a sandbox task directory.

  8. Read the results from the business side, then kill the sandbox.

Prepare the Local Environment

The following example uses Node.js and Puppeteer Core. The business-side environment does not need a full browser because Chromium/Chrome already runs in the browser sandbox.

{
  "name": "browser-use-sandbox-demo",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "e2b": "^2.31.0",
    "puppeteer-core": "^24.0.0"
  }
}

Puppeteer Example

The example flow is:

  1. Create a my-browser-template sandbox.

  2. Wait for the browser service /health endpoint to return 200.

  3. Connect to the cloud browser through CDP.

  4. Open https://example.com, extract page information, and save a screenshot.

import { writeFile } from "node:fs/promises";
import puppeteer from "puppeteer-core";
import { Sandbox } from "e2b";

const TEMPLATE = process.env.E2B_BROWSER_TEMPLATE || "my-browser-template";

const BROWSER_PORT = 3000;
const TARGET_URL = "https://example.com";
const TASK_DIR = "/tmp/browser-task";
const SCREENSHOT_PATH = `${TASK_DIR}/browser-example.png`;

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function toArrayBuffer(bytes) {
  return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
}

async function waitUntilHealthy(sandbox, host, token, timeoutMs = 60_000) {
  const tokenHeader = token ? `-H 'X-Access-Token: ${token}' ` : "";
  const deadline = Date.now() + timeoutMs;

  while (Date.now() < deadline) {
    let result;
    try {
      result = await sandbox.commands.run(
        `curl -sS -o /dev/null -w '%{http_code}' -m 4 ` +
          tokenHeader +
          `https://${host}/health`,
        { timeoutMs: 10_000 },
      );
    } catch (error) {
      result = error;
    }

    const code = (result.stdout || "").trim();
    if (code === "200") {
      return;
    }
    await sleep(2_000);
  }

  throw new Error(`browser service was not ready within ${timeoutMs}ms`);
}

let sandbox;

try {
  sandbox = await Sandbox.create(TEMPLATE, {
    timeoutMs: 300_000,
  });

  const host = sandbox.getHost(BROWSER_PORT);
  const token = sandbox.envdAccessToken;

  await sandbox.files.makeDir(TASK_DIR);
  await waitUntilHealthy(sandbox, host, token);

  const browser = await puppeteer.connect({
    browserWSEndpoint: `wss://${host}/ws/automation`,
    headers: token ? { "X-Access-Token": token } : {},
  });

  const page = await browser.newPage();
  await page.setViewport({ width: 1365, height: 768 });
  await page.goto(TARGET_URL, {
    waitUntil: "networkidle2",
    timeout: 60_000,
  });

  const screenshot = await page.screenshot({ fullPage: true });
  await sandbox.files.write(SCREENSHOT_PATH, toArrayBuffer(screenshot));
  await writeFile("browser-example.png", screenshot);

  const result = await page.evaluate(() => ({
    url: location.href,
    title: document.title,
    text: document.body.innerText.replace(/\s+/g, " ").slice(0, 500),
  }));

  await browser.close();
  console.log(result);
} finally {
  if (sandbox) {
    await sandbox.kill();
  }
}

BrowserUse Integration

For Agents that drive web actions with natural language, let BrowserUse connect to the CDP endpoint exposed by the browser sandbox. The business service creates and destroys the sandbox; BrowserUse only connects to the browser session inside that sandbox.

import asyncio
import os

from browser_use import Agent, BrowserSession, ChatOpenAI
from browser_use.browser import BrowserProfile
from e2b import Sandbox

BROWSER_PORT = 3000


async def main():
    browser_session = None
    sandbox = Sandbox.create(
        template=os.environ.get("E2B_BROWSER_TEMPLATE", "my-browser-template"),
        timeout=600,
    )

    try:
        host = sandbox.get_host(BROWSER_PORT)
        cdp_url = f"wss://{host}/ws/automation"

        browser_session = BrowserSession(
            cdp_url=cdp_url,
            browser_profile=BrowserProfile(
                headless=False,
                keep_alive=True,
            ),
            headers={"X-Access-Token": sandbox._envd_access_token},
        )

        agent = Agent(
            task="Open https://example.com, extract the page title, and summarize the content above the fold.",
            llm=ChatOpenAI(
                model=os.environ.get("QWEN_MODEL", "qwen-vl-max"),
                api_key=os.environ["DASHSCOPE_API_KEY"],
                base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
            ),
            browser_session=browser_session,
            use_vision=True,
        )

        result = await agent.run()
        print(result)
    finally:
        if browser_session is not None:
            await browser_session.stop()
        sandbox.kill()


if __name__ == "__main__":
    asyncio.run(main())

This integration fits search, comparison, form filling, confirmation clicks, and screenshot evidence. For stable outputs, have the Agent write key results as JSON and keep screenshots or HTML snippets for human review and troubleshooting.

Production Recommendations

  • Limit each browser task to an explicit URL scope, and add a domain allowlist when needed.

  • Limit downloadable file types, single-file size, total output size, and task lifetime.

  • Page content may contain prompt injection. Do not let the Agent execute instructions from the page without validation.

  • Isolate login state, cookies, account credentials, and business tokens per task, and inject them at runtime instead of writing them into templates.

  • Record URLs, screenshots, key DOM summaries, tool-call traces, and result file paths.

  • For human observation or debugging, connect noVNC through wss://<sandbox-host>/ws/livestream.

  • If a task needs to continue with Python or Node.js scripts after browser actions, use AIO Sandbox.