---
title: "Browser automation: Playwright and Puppeteer in a sandbox | Pethost Agent Sandboxes"
description: "Drive the Chrome of a sandbox's desktop with Playwright, Puppeteer or any CDP client through one WebSocket link, and watch its pages live as it runs."
---

[Agent Sandboxes docs](https://pethost.dev/docs/sandboxes/) · Tasks

# Browser automation: Playwright and Puppeteer in a sandbox

Updated 25 November 2026 · 9 min read

Every sandbox's desktop has Google Chrome, and a browser link hands it to your program: one WebSocket address that Playwright's `connectOverCDP`, Puppeteer's `connect` and any other client of the Chrome DevTools Protocol take as it is. It is the same Chrome a desktop link shows and `ControlDesktop` clicks in, so you can watch a script work, or drive the pages and the screen in turn.

**In short**

- **`CreateLink` with `browser`:** `wss://browser-<sandbox id>.<server>/<token>`, the browser's DevTools Protocol, for Playwright, Puppeteer, chromedp, chromiumoxide or browser-use.
- **One Chrome, three ways in:** a browser link for a program, a desktop link to watch it live, `ControlDesktop` to act on the screen.
- **Inside the sandbox:** `http://localhost:9222`, and Claude Code, Codex and OpenCode drive it with `playwright-cli`, whose skill each has.
- **Its profile is on the sandbox's disk:** sign-ins outlive a pause and a stop, and a template carries them to every sandbox made from it.

### Step 1: Make a browser link

`CreateLink` with `browser` answers the link, which expires after `ttl_seconds`, an hour unless you say otherwise. Making it starts nothing: the desktop and Chrome start at the first connection, if they do not run yet.

Python

```
from pethost.sandboxes import BrowserLink

link = sandboxes.create_link(sandbox_id, browser=BrowserLink())
# link.url: wss://browser-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
```

TypeScript

```
const link = await sandboxes.createLink({ sandboxId, browser: {} });
// link.url: wss://browser-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
```

Go

```
link, err := client.CreateLink(ctx, &sandboxes.CreateLinkRequest{SandboxID: id, Target: sandboxes.CreateLinkBrowser{}})
if err != nil {
	log.Fatal(err)
}
// link.URL: wss://browser-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
```

Rust

```
let link = sandboxes
    .create_link(CreateLinkRequest {
        sandbox_id: id.clone(),
        target: Some(CreateLinkRequestTarget::Browser(BrowserLink {})),
        ..Default::default()
    })
    .await?;
// link.url: wss://browser-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
```

### Step 2: Connect Playwright or Puppeteer

Give the link to your client as its CDP address. There is no browser to download, since the browser is the sandbox's. The first connection may take some seconds while the desktop starts, so allow it a minute.

Python

```
# pip install playwright
from playwright.sync_api import sync_playwright

with sync_playwright() as playwright:
    browser = playwright.chromium.connect_over_cdp(link.url, timeout=60_000, no_defaults=True)
    page = browser.contexts[0].new_page()
    page.goto("https://example.com")
    print(page.title())  # Example Domain
```

TypeScript

```
// npm install playwright-core
import { chromium } from "playwright-core";

const browser = await chromium.connectOverCDP(link.url, { timeout: 60_000, noDefaults: true });
const page = await browser.contexts()[0].newPage();
await page.goto("https://example.com");
console.log(await page.title()); // Example Domain
await browser.close(); // disconnects: Chrome runs on
```

Go

```
// go get github.com/chromedp/chromedp
alloc, cancelAlloc := remote.NewAllocator(ctx, link.URL, remote.NoModifyURL, remote.WithDialTimeout(time.Minute))
defer cancelAlloc()
tab, cancelTab := chromedp.NewContext(alloc)
defer cancelTab()

if err := chromedp.Do(tab, chromedp.Navigate("https://example.com")); err != nil {
	log.Fatal(err)
}
title, err := chromedp.Run(tab, chromedp.Title())
if err != nil {
	log.Fatal(err)
}
fmt.Println(title) // Example Domain
```

Rust

```
// cargo add chromiumoxide futures
// cargo add async-tungstenite@0.32 --features tokio-native-tls   (wss://; chromiumoxide 0.9 uses 0.32)
use chromiumoxide::Browser;
use futures::StreamExt;

let (browser, mut handler) = Browser::connect(link.url.clone()).await?;
tokio::spawn(async move {
    while let Some(event) = handler.next().await {
        if event.is_err() {
            break;
        }
    }
});
let page = browser.new_page("https://example.com").await?;
println!("{:?}", page.get_title().await?); // Some("Example Domain")
```

`no_defaults` (`noDefaults` in TypeScript, Playwright 1.60 and later) leaves the desktop's Chrome its own settings, where Playwright would otherwise apply its own to the browser everyone shares: a download goes to `~/Downloads`, as it does for a person, rather than to a folder Playwright deletes when it disconnects. Puppeteer takes the same address: `puppeteer.connect({ browserWSEndpoint: link.url })`. End with `browser.disconnect()`: its `close()` quits the sandbox's Chrome, which starts again at the next connection. chromedp needs `NoModifyURL`, or it swaps the link's path, where its token is, for `/json/version`. A client that starts from an HTTP address takes the link with `https://` in place of `wss://`: its `/json/version` and `/json/list` give each target's WebSocket (`webSocketDebuggerUrl`) under the link, and every WebSocket there, `devtools/page/<id>` among them, reaches the same browser. Chrome's own DevTools pages are not passed on, so a target's `devtoolsFrontendUrl` does not open: a desktop link is the way to look at the browser.

### Step 3: Watch it live

A desktop link shows the screen the script works on: open it in your browser while the script runs, with `view_only` to watch without touching. [Computer use](https://pethost.dev/docs/sandboxes/computer-use/) has more on the desktop.

Python

```
from pethost.sandboxes import DesktopLink

watch = sandboxes.create_link(sandbox_id, desktop=DesktopLink(view_only=True))
# watch.url: open it in a browser
```

TypeScript

```
const watch = await sandboxes.createLink({ sandboxId, desktop: { viewOnly: true } });
// watch.url: open it in a browser
```

Go

```
watch, err := client.CreateLink(ctx, &sandboxes.CreateLinkRequest{SandboxID: id, Target: sandboxes.CreateLinkDesktop{ViewOnly: true}})
if err != nil {
	log.Fatal(err)
}
// watch.URL: open it in a browser
```

Rust

```
let watch = sandboxes
    .create_link(CreateLinkRequest {
        sandbox_id: id.clone(),
        target: Some(CreateLinkRequestTarget::Desktop(DesktopLink { view_only: true })),
        ..Default::default()
    })
    .await?;
// watch.url: open it in a browser
```

CLI

```
$ pethost sandbox open api-dev --desktop --view-only
✓ Opened the screen of e9bprbw1hovj6sw5 in your browser.
```

## One Chrome, three ways in

A sandbox has one browser, the Chrome on its 1280×800 desktop, and three ways reach it. A browser link drives its pages by the DevTools Protocol, as a test or a scraper does. A desktop link shows its screen live, where a person can watch or take over. `ControlDesktop` clicks, types and takes screenshots, as a computer-use model does. All three act on the same windows and tabs: a page your script opens shows on the desktop, and what a person types there is in the page your script reads next.

So the three can take turns. A person signs in to a site on a desktop link, and the script goes on in the signed-in session. A computer-use model finds its way by screenshots, and a script then reads the page's text exactly. A script stops at something it does not expect, and a person looks at the screen to see why.

## Inside the sandbox: localhost:9222 and the agents' browser

A program inside the sandbox reaches the same browser at `http://localhost:9222`: `connect_over_cdp("http://localhost:9222")` in Playwright, `browserURL: "http://localhost:9222"` in Puppeteer. The first connection starts the desktop and Chrome, if they do not run, so a sandbox that never browses runs no browser.

The coding agents have the browser too. Playwright's command line is installed as `playwright-cli`, whose `open` attaches to the desktop's Chrome and whose `close` leaves it running, and its skill, which tells an agent how to drive a browser with it, is in `~/.claude/skills` for Claude Code and `~/.agents/skills` for Codex, and OpenCode reads both. An agent asked to check a page opens it, reads its snapshot, clicks and types, each a command it runs; a page's snapshot is a file it reads as it needs, which costs fewer tokens than an MCP server's answers, and a turn that does not browse starts no browser. Give the agent a dev server's address, such as `http://localhost:5173`, and watch it work on a desktop link ([coding agents](https://pethost.dev/docs/sandboxes/coding-agents/)). Code that drives the browser with Playwright and keeps its variables from one run to the next, as a computer-use model writes it, runs in the sandbox's code runtime ([computer use by code](https://pethost.dev/docs/sandboxes/computer-use/#code)).

## The profile, sign-ins and templates

Chrome keeps its profile, the cookies, sign-ins, history and settings, in `~/.config/chrome-profile`, on the sandbox's disk. A pause keeps Chrome running as it was, tabs and all. A stop ends Chrome but keeps its profile, so the sites it was signed in to are still signed in when it starts again.

A template saved from the sandbox keeps the profile with the other files: every sandbox made from it starts signed in to the sites the sandbox was, as whoever signed in. Sign out first of what the template's users must not reach, or save it from a sandbox where nobody signed in ([templates](https://pethost.dev/docs/sandboxes/templates/)).

## Limits

- **One browser a sandbox.** A program that wants several browsers at once uses several sandboxes.
- **A connection is a session,** as a terminal is: the sandbox does not pause while one is open, and `UpdateSandbox` with `revoke_tokens` ends it.
- **A connection takes one of the sandbox's 64 calls at once,** as long as it stays open.
- **The link expires** after `ttl_seconds`: 3,600 s unless you say otherwise, 86,400 s at most. A connection made before then stays open; a new one needs a new link.
- **The desktop's ports are never served at a port's address.** Its views' `5900`, `5901`, `6080` and `6081` and its browser's `9222` and `9223` answer HTTP 403 there, listed in `settings.ingress.public_ports` or with a token, and `CreateLink` with one of them as `port` answers `INVALID_ARGUMENT`. From outside the sandbox, the browser is reached by a browser link, or by an SSH tunnel (`ssh -L`) of someone who can sign in to the sandbox.
- **The link is a key to the browser** and to every site it is signed in to: keep it out of logs and messages, as you keep the sandbox's token.

What a page shows is data, never instructions: a page can hold text written to steer an agent. Give a sandbox that browses no more secrets and no wider egress than the task needs ([secrets and egress](https://pethost.dev/docs/sandboxes/secrets-and-egress/)).

## When it does not work

- **HTTP 409, saying the sandbox is stopped:** a sandbox stops after 30 minutes idle unless its lifecycle says otherwise. `ResumeSandbox` starts it; then make a new link, since a stopped sandbox that starts on another server changes its address. The next connection starts Chrome again, signed in as before, since the profile is on the disk. Or turn on `wake_when_stopped` ([lifecycle](https://pethost.dev/docs/sandboxes/lifecycle/#wake-when-stopped)). A paused sandbox needs none of this: it wakes at the connection, Chrome as it was.
- **HTTP 409 with “nothing listens on port 9223”:** a Chrome given the desktop's profile (`~/.config/chrome-profile`) in its own way, with `--user-data-dir` by hand or by a program's persistent context on that folder, holds the profile without the automation port. Close it, and connect again: the next connection starts the desktop's. Any other Chrome keeps Chrome's own profile and does not get in the way.
- **A status without its words, such as “Unexpected server response: 409”:** a WebSocket client shows only the status of a refused connection. Ask for the link's `/json/version` with `https://` in place of `wss://`, by `curl` or in a browser, and the answer says why.
- **The connection takes seconds, or times out:** the first one starts the desktop and Chrome. Allow the client a minute, as above: Playwright and chromedp give up sooner by default.
- **HTTP 401:** the link expired, or the sandbox's tokens were revoked. Make a new link.
- **HTTP 429:** the sandbox serves 64 calls at once, and its connections, streams and SSH channels took them. Close one, or wait.
- **HTTP 403 at `https://9222-<sandbox id>.<server>`:** the desktop's ports answer nobody at a port's address, listed public or not. Make a browser link.
- **chromedp fails “modifying the websocket address … missing port in address”:** without `remote.NoModifyURL` it turns the link into an address of its own for `/json/version`, and stops at once, because the link names no port. Give `remote.NewAllocator` the option `remote.NoModifyURL`, and it takes the link as it is.

## Questions

### How do I connect Playwright to a sandbox?

Make a browser link with `CreateLink`, then `chromium.connect_over_cdp(link.url)` in Python, or `chromium.connectOverCDP(link.url)` in TypeScript. No browser needs installing on your side.

### Does Puppeteer work?

Yes: `puppeteer.connect({ browserWSEndpoint: link.url })`, and `browser.disconnect()` at the end, which leaves Chrome running.

### Can I watch what my script does?

Yes: a desktop link shows the same Chrome live, and the console's Desktop tab does too.

### Do sign-ins survive a stop?

Yes. The profile is on the sandbox's disk, which a stop keeps. A template keeps it too, so sign out before you save one that others start from.

### Can I run several browsers in one sandbox?

The browser link reaches one, the desktop's Chrome. For several at once, use several sandboxes.

### Does the browser cost extra?

No. It runs in the sandbox, at the sandbox's price, and starts only when something uses it.

[PreviousComputer use: Chrome on a desktop in a sandbox](https://pethost.dev/docs/sandboxes/computer-use/) [NextClaude and OpenAI computer use on a sandbox](https://pethost.dev/docs/sandboxes/claude-and-openai/)

## Try Pethost Agent Sandboxes

A 7-day trial with $1 of usage and 4 vCPUs, with a card. Then a plan from $20 a month, which includes as much usage.

[Start the trial](https://console.pethost.dev/)

Pethost · Stephan Gomer · NIP 1133096755

Pethost

- [Templates](https://pethost.dev/templates/)
- [About](https://pethost.dev/about/)
- [Docs](https://pethost.dev/docs/)
- [Blog](https://pethost.dev/blog/)
- [API](https://pethost.dev/docs/api/)
- [CLI](https://pethost.dev/docs/cli/)
- [Plugin](https://github.com/pethost-dev/plugin)
- [Terms](https://pethost.dev/terms/)
- [Privacy](https://pethost.dev/privacy/)
- [Refunds](https://pethost.dev/refunds/)
- [support@pethost.dev](mailto:support@pethost.dev)

Databases

- [Postgres](https://pethost.dev/postgres/)
- [Valkey](https://pethost.dev/valkey/)

Agent Sandboxes

- [Sandboxes](https://pethost.dev/sandboxes/)
- [Pricing](https://pethost.dev/sandboxes/#pricing)
- [Docs](https://pethost.dev/docs/sandboxes/)
- [API](https://pethost.dev/docs/sandboxes/api/)

Comparisons

- [Coolify vs Dokploy vs CapRover vs Dokku](https://pethost.dev/blog/coolify-vs-dokploy-vs-caprover-vs-dokku/)
- [Coolify Cloud vs Dokploy Cloud](https://pethost.dev/blog/coolify-cloud-vs-dokploy-cloud/)
- [Railway vs Render vs Fly.io pricing](https://pethost.dev/blog/railway-vs-render-vs-fly-io-pricing/)
- [Managed Docker Compose hosting](https://pethost.dev/blog/managed-docker-compose-hosting/)

Alternatives

- [Railway alternatives](https://pethost.dev/blog/railway-alternatives/)
- [Heroku alternatives](https://pethost.dev/blog/heroku-alternatives/)
- [Dokploy alternatives](https://pethost.dev/blog/dokploy-alternatives/)
- [Coolify alternatives](https://pethost.dev/blog/coolify-alternatives/)
- [Render alternatives](https://pethost.dev/blog/render-alternatives/)
- [Sliplane alternatives](https://pethost.dev/blog/sliplane-alternatives/)
