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

# Run a browser on Sail

> A starting point for running Chromium in a Sailbox, with your egress policy applied to the pages it loads.

Give your coding agent [one prompt](#copy-agent-prompt-recommended) to run
Chromium in a [Sailbox](https://docs.sailresearch.com/sailboxes.md) with
[Playwright](https://playwright.dev/python/). The Sailbox's
[egress policy](https://docs.sailresearch.com/sailboxes-egress-policy.md) applies to the browser. It sets the
sites a Sailbox can reach and the secrets Sail adds to its requests.

**Once you're finished, you'll have:**

* Headless Chromium in a Sailbox, printing the title of
  `https://example.com`.
* A sign-in where the browser types a placeholder and the site receives the
  password.

## Copy agent prompt (recommended):

Share this page with your coding agent or paste the prompt below.

```text theme={null}
Follow https://docs.sailresearch.com/browser to run Chromium in a Sailbox.
Install or upgrade the sail Python package. If no Sail credential is set
up, tell me where to enter one, and never print it. Build the image, create a
Sailbox from it, and show me the title of https://example.com loaded in
headless Chromium. Then run the sign-in example and show me that the site
received the secret when the browser typed only a placeholder. Ask me which
site I want to sign in to next, and offer to terminate the Sailbox when I'm
done. Read the gotchas and tell me what you tested live and what still needs
a check.
```

## Manual steps

### 1. Build the image and create a Sailbox

You'll need the latest Sail SDK (`pip install -U sail`) and a
[Sail API key](https://app.sailresearch.com/api-keys) in `SAIL_API_KEY`. If
you've already run `sail auth login` on this machine, you can skip the key.

Run this script on your machine. It prints the Sailbox ID, which later
commands take as `<sailbox-id>`.

```python create_box.py theme={null}
import sail

image = (
    sail.Image.debian_amd64
    .apt_install("xauth")  # for xvfb-run
    .pip_install("playwright")
    .env({"PLAYWRIGHT_BROWSERS_PATH": "/opt/playwright"})  # for every user
    .run_commands("python3 -m playwright install --with-deps chromium")
)
app = sail.App.find(name="browser-demo", mint_if_missing=True)
box = sail.Sailbox.create(app=app, name="browser", image=image)
print(box.sailbox_id)
```

The first create builds the image, which takes about a minute. Later creates
in your organization reuse it.

### 2. Open a page

Save this script on your machine:

```python browse.py theme={null}
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://example.com")
    print(page.title())
    browser.close()
```

Copy it into the Sailbox and run it there:

```bash theme={null}
sail box cp browse.py <sailbox-id>:/root/browse.py
sail box exec <sailbox-id> -- python3 /root/browse.py
```

It prints `Example Domain`.

### 3. Sign in without giving the browser the password

Save this egress policy as `login.json`. It sets `LOGIN_PASSWORD` in the
Sailbox to a placeholder such as `sail_ph_3kTq9...`, and replaces the
placeholder with the secret `DEMO_PASSWORD` in the `password` field of a form
posted to `httpbin.org`, a test site.

```json login.json theme={null}
{
  "env": { "LOGIN_PASSWORD": "DEMO_PASSWORD" },
  "rules": {
    "httpbin.org": [
      {
        "match": { "method": "POST", "path": "/post" },
        "request": { "replace": { "form": { "password": "DEMO_PASSWORD" } } }
      }
    ]
  }
}
```

Store the password as a [secret](https://docs.sailresearch.com/sailboxes-credentials#secrets) in your
organization, create the policy, and set it on the Sailbox:

```bash theme={null}
DEMO_PASSWORD=hunter2 sail secret set DEMO_PASSWORD --from-env DEMO_PASSWORD
sail egress-policy create browser-login --file login.json   # prints the policy ID
sail box egress-policy set <sailbox-id> --egress-policy <policy-id>
```

The script types the placeholder into the form:

```python login.py theme={null}
import json
import os

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.set_content(
        '<form method="post" action="https://httpbin.org/post">'
        '<input name="username"><input name="password" type="password">'
        "<button>Sign in</button></form>"
    )
    page.fill('input[name="username"]', "alice")
    page.fill('input[name="password"]', os.environ["LOGIN_PASSWORD"])
    page.click("button")
    page.wait_for_url("https://httpbin.org/post")
    print(json.loads(page.inner_text("body"))["form"])
    browser.close()
```

```bash theme={null}
sail box cp login.py <sailbox-id>:/root/login.py
sail box exec <sailbox-id> -- python3 /root/login.py
```

```text Output theme={null}
{'password': 'hunter2', 'username': 'alice'}
```

The browser typed only the placeholder. `hunter2` is in the output because
httpbin sends back what it received.

For your own site, name its host, the path its form posts to, and its
password field in the policy. A site that signs in with a JSON request needs
`json` in place of `form`, with a JSON Pointer such as `"/password"` as the
key. The [reference](https://docs.sailresearch.com/reference/egress-policy.md#env) covers `form` and `json`.

## Run Chromium with a window

A Sailbox has no screen. To give Chromium a window, add `headless=False` to
`launch` and run the script under `xvfb-run`, which provides a virtual
screen:

```bash theme={null}
sail box exec <sailbox-id> -- xvfb-run -a python3 /root/browse.py
```

## Watch or take over the browser

Launch Chromium with a debugging port, and keep the script running while you
watch, for example with `page.wait_for_timeout(600_000)` before
`browser.close()`:

```python theme={null}
browser = p.chromium.launch(args=["--remote-debugging-port=9222"])
```

Start the script with `sail box exec` as before. In a second terminal on your
machine, run
[`sail box shell <sailbox-id>`](https://docs.sailresearch.com/reference/cli#sail-box-shell). While that
shell is open, the Sailbox's port 9222 is also on `localhost:9222` on your
machine, unless that port is already in use there. Open `chrome://inspect` in
Chrome and choose **inspect** under the page. You see the page as it changes
and can click and type in it.

When you're done, terminate the Sailbox with
`sail box terminate <sailbox-id>`.

## Gotchas

> [accordion] Submitting a form fails with ERR\_HTTP\_RESPONSE\_CODE\_FAILURE
>
> Sail answered with status 502 and didn't send the form. The rule matched,
> but the placeholder was in a field it doesn't name, or the form uploads
> files (`multipart/form-data`), which a rule can't change.

> [accordion] The site rejects the password
>
> The rule probably didn't match, and the site received the placeholder.
> Check the rule's host, method, and path.

> [accordion] How do I turn on Chromium's sandbox?
>
> Playwright starts Chromium without its sandbox. Chromium won't enable it
> as root. Add a user to the image with
> `.run_commands("useradd -m browser")`, pass `chromium_sandbox=True` to
> `launch`, and run the script as that user:
>
> ```bash theme={null}
> sail box cp browse.py <sailbox-id>:/home/browser/browse.py
> sail box exec --user browser <sailbox-id> -- python3 /home/browser/browse.py
> ```
