← Blog

BLOG

Claude Code Browser Control: A Practical Setup Guide

Learn how to give Claude Code browser control with Playwright and CDP, choose an MCP or script workflow, and operate remote Chromium with verifiable checks.

10 min readRemote Browser
Ivory computer towers connected across terracotta platforms in a quiet desert landscape
The infrastructure behind your browserREMOTE BROWSER / ILLUSTRATION

Claude Code browser control means giving Claude Code a way to interact with a real browser: open pages, inspect rendered content, take actions, and verify what changed. Claude Code does not turn a browser into a built-in capability on its own. You provide that capability through a tool, such as a Playwright script or an MCP server, and connect the tool to a browser runtime.

For a simple, inspectable setup, run a small Playwright script that connects over the Chrome DevTools Protocol (CDP) to a browser session. Claude Code can invoke the script from your project, while your code controls which pages and actions are available. This keeps model reasoning separate from browser execution and makes timeouts, permissions, and verification explicit.

Choose how Claude Code reaches the browser

There are two common ways to expose browser actions to Claude Code:

  • A project script: Claude Code runs a TypeScript or JavaScript program in the repository. The program uses Playwright and connects to a local or remote browser. This is straightforward when you want to control the available operations in code.
  • An MCP server: Claude Code calls browser tools exposed by a configured MCP server. The server handles the browser connection and provides named operations. This can make browser actions easier to discover and reuse, but the MCP server must support the browser runtime you intend to use.

A CDP endpoint is a browser connection, not an MCP server. If you choose MCP, check how that server connects to Chromium and whether it accepts your browser provider’s endpoint. For the script approach below, Playwright connects directly to a CDP endpoint supplied for an active browser session.

ApproachBest fitMain trade-off
Playwright scriptA bounded workflow with project-specific checksYou write and maintain the allowed actions
Browser MCP serverReusable browser tools called through MCPCapabilities and configuration depend on the server
Local browser automationDevelopment against a browser on your machineThe browser shares your local environment and availability

For Claude Code browser control in a repository, start with a script if you need deterministic steps and assertions. Add an MCP server when multiple workflows benefit from a shared tool interface, or when you want Claude Code to call higher-level browser actions instead of invoking scripts.

Connect Playwright to a remote session

A remote browser separates the code that requests an action from the Chromium process that renders the page. You run Playwright in your project and connect it to the browser session through CDP. The browser provider supplies the session endpoint; keep it in an environment variable rather than writing credentials or tokens into source code.

Install Playwright in the project:

npm install playwright

Use the following script as a small starting point. It reads the endpoint and target URL from the environment, navigates to the page, and reports a limited amount of page information. The script does not submit forms or make changes to the site.

import { chromium } from "playwright";

const endpoint = process.env.BROWSER_WS_ENDPOINT;
const targetUrl = process.env.TARGET_URL;

if (!endpoint || !targetUrl) {
  throw new Error("Set BROWSER_WS_ENDPOINT and TARGET_URL.");
}

const browser = await chromium.connectOverCDP(endpoint);

try {
  const context = browser.contexts()[0];
  if (!context) {
    throw new Error("The connected browser has no available context.");
  }

  const page = context.pages()[0] ?? await context.newPage();

  await page.goto(targetUrl, {
    waitUntil: "domcontentloaded",
    timeout: 30_000,
  });

  const title = await page.title();
  const heading = await page.locator("h1").first().textContent()
    .catch(() => null);

  console.log(JSON.stringify({
    url: page.url(),
    title,
    heading: heading?.trim() ?? null,
  }, null, 2));
} finally {
  await browser.close();
}

Run the script with your project’s TypeScript runner, for example npx tsx scripts/inspect-page.ts, after setting the two environment variables. Use the exact WebSocket endpoint format provided for your session; do not assume that a generic HTTP URL is interchangeable with a CDP WebSocket endpoint.

Playwright documents this connection method in its `connectOverCDP` API reference. Playwright notes that CDP connections are supported for Chromium-based browsers and are lower fidelity than its native Playwright protocol connection. That distinction matters if your workflow depends on Playwright-specific behavior. For a browser exposed through CDP, test the particular APIs and context behavior your task requires.

The example closes the Playwright connection in finally so the script does not leave its client connection open after an error. Browser-session teardown is a separate lifecycle decision: follow the provider’s instructions for whether to stop the remote session, preserve it, or disconnect while keeping it available. Avoid placing a provider-specific stop call in shared project code unless you have confirmed its endpoint and ownership semantics.

Give Claude Code a bounded task

Claude Code can run the script through the project’s normal command workflow. Describe the task in terms of the permitted page, the actions allowed, and the evidence needed to call it complete. For example:

Open the staging account page with the browser script. Read the page heading and status. Do not submit or change anything. Report the URL and visible status text.

That instruction is more useful than asking an agent to “use the browser” without defining the scope. For a workflow that must change data, name the permitted action and require a post-action check. A click is not proof of success: verify the resulting URL, visible confirmation, or updated record state.

For repeatable jobs, put the browser steps in a script rather than asking the model to invent selectors each run. The script can expose a small set of inputs, such as a record ID or a search term, and validate them before navigation. Keep the operation specific enough that it cannot turn an intended lookup into an unbounded browsing session.

Claude Code browser control works best when the program returns concise evidence rather than a full HTML document. Capture the current URL, relevant visible text, and any state needed for the next decision. Large DOM dumps increase noise and can expose unrelated page data. If a page needs more inspection, collect a focused region or a screenshot and use the remote session’s live viewer when visual debugging is useful.

Make actions reliable and inspectable

Browser automation fails for ordinary reasons: a page is still loading, a selector matches multiple elements, the session has expired, or an application changed its UI. A useful control loop has four steps:

  1. Establish state. Navigate to the intended page and confirm its URL or a stable page landmark.
  2. Identify the target. Prefer accessible locators such as getByRole with a clear name, or stable test IDs where the application provides them.
  3. Act once. Use a bounded timeout and avoid replaying non-idempotent actions such as payments, submissions, or account changes without checking the outcome.
  4. Verify the result. Assert a visible confirmation, expected state change, or destination URL before reporting success.

Avoid fixed sleeps as the primary synchronization method. Waiting for a specific locator or navigation condition is usually more robust than pausing for an assumed number of seconds. When a step times out, capture enough diagnostic context to identify the failure: current URL, relevant locator state, and a screenshot if available. Use bounded retries only for operations that are safe to repeat.

Keep credentials and session endpoints out of prompts, logs, and committed files. Load secrets through the environment or your organization’s secret-management workflow. Use a separate browser session for tasks that should not share cookies or storage. Persistent profiles can be useful for authenticated workflows, but they also carry account state across runs; decide when that persistence is appropriate and who can access the profile.

Remote Browser provides hosted Chromium sessions with CDP access and supports Playwright, Puppeteer, and Selenium workflows. Its live viewer can help an operator inspect a running session, while configurable browser settings, persistent profiles, session isolation, and usage controls address different operational needs. These are runtime capabilities, not substitutes for application-level authorization or checks in your script. Review the Remote Browser documentation for current connection details and configuration.

Decide when remote Chromium is appropriate

Local Chromium is often the quickest choice for a developer debugging a page on their own machine. A remote browser is useful when the automation must run from a worker or CI environment, when the browser should be isolated from the agent host, or when an operator needs to view a session remotely. It also moves browser installation and execution away from the machine running Claude Code.

Remote execution introduces its own operational concerns. Your script depends on network access to the session endpoint, and you need a policy for session creation, cleanup, persistence, and failure recovery. Browser settings and proxy options should match the target site and the task’s requirements; do not assume a particular configuration will work on every site. Check current usage limits and pricing on the pricing page before estimating workload costs.

CriterionLocal ChromiumHosted Chromium
Browser processRuns on the developer or worker machineRuns in a provider-managed browser session
ConnectionLocal Playwright launch or attachUsually connects through a remote endpoint such as CDP
DebuggingInspect locally with developer toolsUse the provider’s live-viewing and session tools
State managementLocal browser profile and storageSession and profile behavior depends on configuration
Operational workInstall, update, and isolate local browser processesManage remote sessions, endpoint access, and usage

For more on the runtime distinction, see remote browsers for AI agents. If the main question is how browser actions map to remote sessions, remote control browser covers the broader control model.

Set production boundaries before scaling

Treat the browser endpoint like a credential. Anyone who can use it may be able to interact with the session, so restrict where it is stored and which process can read it. Avoid printing it in error output. If a session is intended for one task, prevent unrelated jobs from sharing that session or profile.

Before deploying Claude Code browser control beyond development, decide:

  • Allowed destinations: constrain workflows to the sites and environments they need.
  • Allowed actions: separate read-only inspection from actions that change data or account state.
  • Session ownership: define who creates, observes, reuses, and stops sessions.
  • Failure behavior: specify what should happen after an expired session, timeout, or unexpected page.
  • Audit evidence: retain the minimum logs needed to explain what the script observed and did, without recording secrets or unnecessary page content.
  • Cost and capacity: estimate expected session use and check current plan limits and pricing before increasing concurrency.

For a high-impact action, require an explicit approval step or a separate review before execution. The browser can render the same buttons a human sees, but the automation still needs application-specific rules about which actions are permitted. Do not infer permission from a button being visible.

A practical starting point

Start with a read-only script and one known page. Confirm that Playwright can connect to the session, navigate, and return a small set of expected details. Then add one action at a time, pairing each action with a check that proves its effect. This makes it easier to identify whether a failure comes from Claude Code’s instruction, your script, the page, or the remote session.

Use MCP when a shared browser tool interface is valuable; use a project script when you want a small, explicit workflow that is easy to test. In both cases, Claude Code browser control is the combination of an agent, a defined tool boundary, and a browser runtime. Keeping those parts separate gives you a workflow that can be inspected, tested, and changed without treating every browser action as an opaque model decision.