> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Browser

> A real Chromium in every sandbox: drive it with Playwright or Puppeteer from inside the sandbox or from your own code, watch it live, and keep its tabs and logins across sleep.

Many tasks need a real web browser: agents that browse the web, scrapers, end-to-end tests, or bots that log in and
fill in forms. Running that browser on your own machine or servers is awkward and risky. **Every sandbox on Fibre's
default image has a browser of its own**: Chromium, with Playwright and ChromeDriver already installed, and
support for Puppeteer.

There are two ways to use it, depending on where your code runs:

| | Script inside the sandbox | Drive it from your code |
| - | - | - |
| Where your code runs | In the sandbox, next to the browser | In your app or on your laptop |
| How it connects | Playwright launches Chromium directly | Over the DevTools protocol, with `cdp_url` |
| Good for | Scraping jobs, test suites, an agent's own scripts | An agent in your app that controls a page step by step |
| Watch it live | With the live view | With the live view |

## Run a browser script inside the sandbox

The quickest way to start is to write a Playwright script, run it inside the sandbox, and read its output. This
example opens Hacker News, reads the five top stories, and takes a screenshot of the page.

**1. Start a sandbox**

```bash title="CLI" run theme={null}
SBX=$(fibre create --size medium --lifetime 15m --label docs=browser --json | jq -r .id)
```

```typescript title="TypeScript" run theme={null}
import { Sandbox } from "@fibre-dev/sdk";

const sbx = await Sandbox.create({ size: "medium", lifetime: 900, labels: { docs: "browser" } });
```

```python title="Python" run theme={null}
from fibre import Sandbox

sbx = Sandbox.create(size="medium", lifetime=900, labels={"docs": "browser"})
```

```bash title="curl" run capture=SBX=.id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"size": "medium", "lifetime_sec": 900, "labels": {"docs": "browser"}}'
```

**2. Write the script**

```bash title="CLI" run theme={null}
fibre exec "$SBX" -i -- sh -c 'mkdir -p /work && cat > /work/top.cjs' <<'JS'
const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto("https://news.ycombinator.com");
  const stories = await page.$$eval(".titleline > a", (links) =>
    links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href })));
  await page.screenshot({ path: "/work/front-page.png" });
  console.log(JSON.stringify(stories, null, 2));
  await browser.close();
})();
JS
```

```typescript title="TypeScript" run theme={null}
await sbx.files.write("/work/top.cjs", `
const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto("https://news.ycombinator.com");
  const stories = await page.$$eval(".titleline > a", (links) =>
    links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href })));
  await page.screenshot({ path: "/work/front-page.png" });
  console.log(JSON.stringify(stories, null, 2));
  await browser.close();
})();
`);
```

```python title="Python" run theme={null}
sbx.files.write("/work/top.cjs", """
const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto("https://news.ycombinator.com");
  const stories = await page.$$eval(".titleline > a", (links) =>
    links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href })));
  await page.screenshot({ path: "/work/front-page.png" });
  console.log(JSON.stringify(stories, null, 2));
  await browser.close();
})();
""")
```

```bash title="curl" run theme={null}
cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/top.cjs" \
  -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @-
const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto("https://news.ycombinator.com");
  const stories = await page.$$eval(".titleline > a", (links) =>
    links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href })));
  await page.screenshot({ path: "/work/front-page.png" });
  console.log(JSON.stringify(stories, null, 2));
  await browser.close();
})();
EOF
```

Playwright and its Chromium are already installed in the default image, so `require("playwright")` works without
an `npm install`.

**3. Run it and read the result**

```bash title="CLI" run theme={null}
fibre exec "$SBX" --timeout 2m -- node /work/top.cjs | jq '.[0]'   # {"title": "…", "url": "https://…"}

fibre cp "$SBX:/work/front-page.png" front-page.png
```

```typescript title="TypeScript" run theme={null}
const run = await sbx.run(["node", "/work/top.cjs"], { timeout: 120 });
const stories = JSON.parse(run.stdout);
console.log(stories[0]); // { title: '…', url: 'https://…' }

const png = await sbx.files.readBytes("/work/front-page.png");
console.log(`screenshot: ${png.byteLength} bytes`);
```

```python title="Python" run theme={null}
import json

run = sbx.run(["node", "/work/top.cjs"], timeout=120)
stories = json.loads(run.stdout)
print(stories[0])  # {'title': '…', 'url': 'https://…'}

png = sbx.files.read_bytes("/work/front-page.png")
print(f"screenshot: {len(png)} bytes")
```

```bash title="curl" run capture=TOP=.command_id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["node", "/work/top.cjs"]}'
```

```bash title="curl: the result" run theme={null}
curl -sSN "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$TOP/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY"
curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/front-page.png" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -o front-page.png
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> "exit_code":0
> ```
>
> The script prints the five stories as JSON:
>
> ```json title="stories" theme={null}
> [
>   {
>     "title": "…",
>     "url": "https://…"
>   }
> ]
> ```

> [!TIP]
>
> You can use Python in the same way. Install Playwright with `pip install playwright` in a
> [virtual environment](https://docs.fibre.dev/sandboxes/sizes.md#install-what-is-missing), then point it at the installed browser with
> `executable_path="/usr/local/bin/google-chrome"`.

## Drive the browser from your code

Sometimes the agent runs in **your own app**, not in the sandbox. It then needs to control the browser remotely,
one step at a time: look at the page, decide what to do, click. For that, ask the sandbox for its browser. You get
back two links:

```bash title="CLI" run theme={null}
LINKS=$(fibre browser "$SBX" --json)
CDP=$(echo "$LINKS" | jq -r .cdp_url)
echo "$LINKS" | jq -r .live_view_url   # open it to watch
```

```typescript title="TypeScript" run theme={null}
const { cdpUrl, liveViewUrl, expiresAt } = await sbx.browser();
console.log(liveViewUrl); // open it to watch
```

```python title="Python" run theme={null}
links = sbx.browser()
cdp_url, live_view_url = links.cdp_url, links.live_view_url
print(live_view_url)  # open it to watch
```

```bash title="curl" run capture=CDP=.cdp_url theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/browser" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "cdp_url": "…",
>   "live_view_url": "…",
>   "expires_at": "…"
> }
> ```

| Link | For | Who may have it |
| - | - | - |
| `cdp_url` | Your code: Playwright `connectOverCDP`, Puppeteer `connect` | **Only your backend. It is a password**: whoever has it controls the browser |
| `live_view_url` | A person: shows the screen, passes on clicks and keys | Safe to show to your user |

`cdp_url` uses the Chrome DevTools Protocol (CDP), the standard way for automation tools to control Chrome. Connect
to it with Playwright from your own machine or server:

```typescript title="TypeScript" norun reason="needs Playwright installed where your code runs" theme={null}
import { chromium } from "playwright";

const browser = await chromium.connectOverCDP(cdpUrl);
const context = browser.contexts()[0];                    // the browser's own context: its cookies and logins
const page = context.pages()[0] ?? (await context.newPage());

await page.goto("https://github.com/login");
await page.fill("#login_field", process.env.GH_USER!);
// … your agent decides the next step from page content or a screenshot
```

```python title="Python" norun reason="needs Playwright installed where your code runs" theme={null}
import os

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(cdp_url)
    context = browser.contexts[0]  # the browser's own context: its cookies and logins
    page = context.pages[0] if context.pages else context.new_page()

    page.goto("https://github.com/login")
    page.fill("#login_field", os.environ["GH_USER"])
    # … your agent decides the next step from page content or a screenshot
```

**Use the browser's existing context, as above, rather than creating a new one.** The existing context is where
the browser keeps its cookies and logins, and it is what survives a sleep.

The DevTools address also answers the standard discovery requests, so any tool that speaks CDP can find the
browser:

```bash title="CLI" run theme={null}
curl -sS "${CDP/ws/http}/json/version" | jq -r .Browser   # Chrome/1…
```

```typescript title="TypeScript" run theme={null}
const version = await fetch(`${cdpUrl.replace(/^ws/, "http")}/json/version`).then((r) => r.json());
console.log(version.Browser); // Chrome/1…
```

```python title="Python" run theme={null}
import json
from urllib.request import urlopen

version = json.load(urlopen(cdp_url.replace("ws", "http", 1) + "/json/version"))
print(version["Browser"])  # Chrome/1…
```

```bash title="curl" run theme={null}
curl -sS "${CDP/ws/http}/json/version"
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "Browser": "…",
>   "webSocketDebuggerUrl": "…"
> }
> ```

The links work for an hour. To choose a different duration, pass `{"ttl_sec": …}` (between 60 seconds and a day,
but never past the sandbox's lifetime, if it has one). You can ask for fresh links at any time.

## Watch it live

Open `live_view_url` in any browser. **You see the page exactly as the agent sees it, and you can click and type
into it yourself.** You could show it to your user while their agent books a flight for them, or open it yourself
to find out why a script is stuck.

The live view only shows the screen and passes on clicks and key presses. It cannot run code or reach the
DevTools, so it is safe to share.

## Logins that last

The browser is part of the sandbox, so **when the sandbox sleeps, the browser sleeps with it**, together with its
open tabs, cookies, local storage and the page it was on. The next connection finds it exactly as it was.

That makes **"log in once, reuse for days"** simple. Give each user a sandbox for the site they want automated.
The user logs in once through the live view, and from then on your agent uses that logged-in session. Between uses,
the sandbox sleeps: nothing for compute, and its saved state counts towards your storage.

## A browser from the start

If you know you will need the browser, ask for it when you create the sandbox with `"needs": ["browser"]`. The
browser then starts together with the sandbox, and the create answer already includes the links under `browser`.
Such a sandbox uses the `vm` runtime unless you choose another one, because **browsers run faster there**.

```bash title="CLI" run theme={null}
READY=$(fibre create --needs browser --lifetime 10m --label docs=browser --json | jq -r .id)
fibre get "$READY"   # runtime: vm (needs:browser)
```

```typescript title="TypeScript" run theme={null}
const ready = await Sandbox.create({ needs: ["browser"], lifetime: 600, labels: { docs: "browser" } });
console.log(ready.runtime, ready.runtimeReason); // vm needs:browser
```

```python title="Python" run theme={null}
ready = Sandbox.create(needs=["browser"], lifetime=600, labels={"docs": "browser"})
print(ready.runtime, ready.runtime_reason)  # vm needs:browser
```

```bash title="curl" run capture=B=.id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"needs": ["browser"], "lifetime_sec": 600, "labels": {"docs": "browser"}}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "runtime": "vm",
>   "runtime_reason": "needs:browser",
>   "browser": {
>     "cdp_url": "…",
>     "live_view_url": "…",
>     "expires_at": "…"
>   }
> }
> ```

## Close it

When you no longer need the browser, close it with `closeBrowser()` (or `DELETE /v1/sandboxes/{id}/browser`). This
cancels every link, closes their connections and stops the browser. The sandbox itself keeps running.

## Good to know

A few details about how the browser behaves:

| | |
| - | - |
| Browsers per sandbox | One, shared by every connection |
| Sleep | A sandbox with its browser open sleeps once **no client is connected** and nothing else happens for its idle timeout |
| Image | Needs Fibre's default image, or your own image with Chrome at the usual path |
| Inside the sandbox | `CHROME_PATH`, `PUPPETEER_EXECUTABLE_PATH` point at the installed browser |

## Clean up

```bash title="CLI" run theme={null}
fibre delete "$SBX" "$READY"
rm -f front-page.png
```

```typescript title="TypeScript" run theme={null}
await sbx.delete();
await ready.delete();
```

```python title="Python" run theme={null}
sbx.delete()
ready.delete()
```

```bash title="curl" run theme={null}
for id in "$SBX" "$B"; do
  curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$id" -H "Authorization: Bearer $FIBRE_API_KEY"; echo
done
rm -f front-page.png
```

## Related

> [card] [Desktop](https://docs.fibre.dev/connect/desktop.md)
>
> A whole desktop, not only a browser, for computer-use agents.

> [card] [Public URLs](https://docs.fibre.dev/connect/public-urls.md)
>
> Test your own app with the browser in the same sandbox.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.