← Blog

BLOG

Gemini Browser Agent: Build a Safe Remote Browser Workflow

Build a Gemini browser agent with Playwright and hosted Chromium, and learn how to validate actions, manage sessions, and debug failures.

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

A Gemini browser agent uses a Gemini model to interpret a web task and choose what to do next, while browser automation software performs the actual interactions. Gemini is the reasoning layer; Playwright or another automation tool controls the browser; and a local or hosted Chromium session supplies the page, cookies, and execution environment.

This guide shows how to connect those pieces using Playwright over the Chrome DevTools Protocol (CDP). The example deliberately gives Gemini a narrow choice: request one approved button click or stop. That makes the boundary between a model decision and a browser action explicit.

What does a Gemini browser agent need?

A working agent needs more than a model prompt. At minimum, it needs four components:

  1. A Gemini integration that sends the model a task and a representation of the page.
  2. An observation layer that collects relevant page text, structured element information, or screenshots.
  3. An action executor that translates approved decisions into browser operations.
  4. A browser runtime that hosts Chromium and maintains the session while the task runs.

The model does not directly control Chromium simply because it receives a screenshot. Your application must interpret its output, validate the requested action, and execute it through a tool such as Playwright.

A typical request loop looks like this:

Task → observe page → ask Gemini → validate decision
     → execute approved action → observe result → continue or stop

For predictable tasks, keep as much of this loop deterministic as possible. For example, let Gemini decide whether a known page is ready for a particular action, but use a fixed Playwright locator to execute that action.

Choose the browser-control approach

There are several ways to build a Gemini browser agent. The right choice depends on how much freedom the workflow needs and how much control you want over execution.

ApproachHow it worksBest fitMain trade-off
Gemini plus explicit Playwright toolsYour application defines browser operations and validates model decisions.Bounded workflows and custom approval rules.You build the observation, tool-calling, and recovery logic.
Browser-agent framework with a Gemini integrationA framework manages some combination of planning, browser tools, and the agent loop.Prototyping multi-step tasks without building every component.Tool behavior and model support depend on the framework and version.
Gemini plus visual interactionThe model interprets screenshots and proposes actions based on what it sees.Interfaces where useful DOM information is unavailable.Visual ambiguity, changing layouts, and coordinate errors require extra validation.
Deterministic Playwright without an agentA script follows predefined locators and conditions.Stable, repeatable workflows with known page structure.Less adaptable when the page or task varies.

These approaches can all use a local browser or, where supported, a remote browser. A hosted session changes where Chromium runs; it does not automatically make the model's decisions correct or safe.

For a broader discussion of the runtime layer, see remote browsers for AI agents.

How Gemini, Playwright, and a remote browser fit together

In the setup below, the application uses Gemini for a decision and Playwright for execution:

  • Gemini: evaluates a screenshot against a specific task.
  • Playwright: captures the screenshot, locates an approved button, clicks it, and checks the result.
  • CDP: connects Playwright to an existing Chromium browser.
  • Remote Browser: provides hosted Chromium sessions that can be accessed through CDP.

The model API and the browser connection are separate services. You need credentials for Gemini and a CDP endpoint for your browser session. Keep both out of source control and application logs.

Playwright's `connectOverCDP` documentation describes the connection method. It is Chromium-specific, and Playwright notes that CDP connections have lower fidelity than its native Playwright protocol connection. Test the browser operations your workflow actually requires.

What to send Gemini

A screenshot is useful when layout or visible state matters. Text and structured element descriptions are often more compact and easier to validate. A production agent may combine them, but should send only the information required for the current decision.

Before transmitting page content to a model, consider whether it contains customer data, authentication information, or confidential text. Apply your organization's data-handling rules to both screenshots and DOM-derived observations.

Build a bounded Gemini browser agent in TypeScript

This example connects to a remote Chromium session, opens a test page, and asks Gemini whether to click an approved button. It is intentionally a single decision, not a general-purpose autonomous browsing loop.

Use a test page you control with:

  • A button whose accessible name is Show details.
  • A visible Details loaded message that appears after the button is clicked.

The model can return CLICK or STOP. Application code, not the model, determines the locator and verifies the outcome.

1. Install dependencies and configure the session

Install the Playwright library and Google's Gen AI SDK:

npm install playwright @google/genai

Use a TypeScript-capable Node.js environment. Create a hosted Chromium session through your browser provider and obtain its CDP endpoint using that provider's documentation. Then set:

  • GEMINI_API_KEY: your Gemini API key.
  • GEMINI_MODEL: a Gemini model available to your account that accepts image input.
  • CDP_URL: the session's CDP endpoint, including any authentication the provider requires.
  • TEST_PAGE_URL: the URL of your controlled test page.

Consult Remote Browser documentation for current session and connection instructions. The endpoint is a credential: anyone who can use it may be able to control the associated browser session.

2. Observe, decide, act, and verify

import { GoogleGenAI } from "@google/genai";
import { chromium } from "playwright";

function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing environment variable: ${name}`);
  return value;
}

async function main(): Promise<void> {
  const apiKey = requiredEnv("GEMINI_API_KEY");
  const model = requiredEnv("GEMINI_MODEL");
  const cdpUrl = requiredEnv("CDP_URL");
  const testPageUrl = requiredEnv("TEST_PAGE_URL");

  const ai = new GoogleGenAI({ apiKey });
  const browser = await chromium.connectOverCDP(cdpUrl);

  try {
    // Use the existing context exposed by the remote browser session.
    const context = browser.contexts()[0];
    if (!context) throw new Error("No browser context available");

    const page = await context.newPage();

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

      const screenshot = await page.screenshot({ type: "png" });

      const response = await ai.models.generateContent({
        model,
        contents: [
          {
            role: "user",
            parts: [
              {
                text:
                  'Task: If the page visibly offers a "Show details" ' +
                  "button, reply CLICK. Otherwise reply STOP. " +
                  "Return exactly one word: CLICK or STOP.",
              },
              {
                inlineData: {
                  mimeType: "image/png",
                  data: screenshot.toString("base64"),
                },
              },
            ],
          },
        ],
      });

      const decision = (response.text ?? "").trim();

      if (decision === "STOP") {
        console.log("Stopped: no action requested.");
        return;
      }

      // Reject unexpected or ambiguous model output.
      if (decision !== "CLICK") {
        throw new Error("Model returned an invalid decision");
      }

      const button = page.getByRole("button", {
        name: "Show details",
        exact: true,
      });

      // A model decision is not sufficient: require one visible target.
      if ((await button.count()) !== 1 || !(await button.isVisible())) {
        throw new Error("Approved button is missing or ambiguous");
      }

      await button.click({ timeout: 10_000 });

      const result = page.getByText("Details loaded", { exact: true });
      await result.waitFor({ state: "visible", timeout: 10_000 });
      console.log("Verified: details loaded.");
    } finally {
      await page.close();
    }
  } finally {
    await browser.close();
  }
}

main().catch((error: unknown) => {
  // Avoid logging endpoint URLs, screenshots, or full page content.
  console.error(error instanceof Error ? error.message : "Run failed");
  process.exitCode = 1;
});

The example uses the default context returned by the connected browser. Confirm that your provider exposes a context and permits new pages in it. browser.close() disconnects the Playwright client; check your provider's session-lifecycle documentation to determine whether a separate stop call is required. A finally block cannot guarantee cleanup if the process is forcibly terminated, so configure session timeouts or external cleanup as well.

3. Understand the example's limits

This example is useful because the model's authority is small. It cannot supply a selector, navigate to an arbitrary URL, or click a different button. Unexpected output fails closed.

It is not a complete security boundary. The screenshot is untrusted page content, and a malicious page could still influence Gemini's decision. The fixed action, target checks, and controlled test page limit the consequences. A production implementation should also validate navigation destinations, handle redirects, set an overall deadline, and apply authorization checks before sensitive actions.

If the task is always “click this known button when it exists,” use deterministic Playwright instead. The Gemini decision becomes more useful when interpreting visual state is genuinely necessary.

Design the observation and action loop

To extend the example into a multi-step agent, define a small set of operations and a structured response format before giving the model broader access.

For example, your application might support inspect, click, fill, and stop. Each operation should have a schema, allowed targets, and a clear failure response. A fill action should not automatically authorize submitting a form.

For each step:

  1. Observe: capture the current URL and the minimum relevant page state.
  2. Decide: ask Gemini for one action, not an unrestricted script.
  3. Validate: check the action against the task, allowed domains, target rules, and user authorization.
  4. Execute: perform the action with explicit timeouts.
  5. Verify: inspect the resulting page state before continuing.

Treat a model-generated selector or element identifier as a proposal, not as authority. Resolve it against the current page and reject it if it matches multiple elements, points outside the permitted scope, or no longer exists.

Set a maximum number of steps and a total runtime limit. If verification fails, stop or use a bounded recovery path. Do not repeatedly retry a payment, account change, or submission simply because the confirmation page did not load: the original action may already have succeeded.

Protect credentials and control sensitive actions

Browser agents combine several sensitive assets: model credentials, CDP access, page content, and sometimes authenticated browser state. Protect each independently.

  • Keep credentials server-side. Do not expose Gemini keys or CDP endpoints in browser code, screenshots, logs, or support tickets.
  • Isolate sessions. Use separate browser sessions and profiles for different users or tenants. Avoid sharing an authenticated context across unrelated tasks.
  • Restrict destinations. Enforce an allowlist where practical, including checks after redirects. Network-level restrictions can provide an additional layer.
  • Require approval for consequential actions. Purchases, messages, deletions, and account changes should have an explicit authorization step.
  • Treat pages as untrusted. Instructions embedded in a page can attempt to override the task. They should not change your tool permissions or reveal secrets.
  • Limit retained artifacts. Screenshots, traces, and page text may contain personal data. Define access and retention policies before enabling them.

A persistent profile can preserve a login between runs, but it also preserves valuable credentials and state. Use one only when the workflow needs it, and decide how it will be revoked or reset.

Debug failures across the model and browser layers

A failed Gemini browser agent run is not always a model failure. Separate the layers when investigating:

SymptomLikely area to inspectUseful next check
CDP connection failsEndpoint, credentials, network, or session lifecycle.Confirm the session is active and the endpoint is accessible from the worker.
Screenshot shows the wrong pageNavigation, redirects, authentication, or timing.Inspect the current URL and browser state before the model call.
Gemini requests an invalid actionPrompt, output format, or page ambiguity.Log a sanitized decision and reject anything outside the allowed schema.
Playwright cannot find the targetLocator, page state, iframe, or timing.Check the accessible name and whether the target is in the expected frame.
Click succeeds but task is unverifiedAsync application behavior or an incorrect success condition.Check for a durable confirmation rather than assuming the click completed the task.

A live viewer can help an operator inspect the browser state during a difficult run. Remote Browser provides a live viewer alongside its hosted sessions; use it with appropriate access controls because the session may expose authenticated pages.

For production, record a task ID, session ID, step count, action type, timing, and verification result. Add screenshots or traces selectively, with redaction and retention controls. This makes it possible to distinguish a browser connectivity issue from an incorrect model decision without logging every page in full.

Run the agent on hosted Chromium

Remote Browser supplies the browser runtime for this architecture: hosted Chromium sessions accessible over CDP, with compatibility for tools including Playwright. It also provides persistent profiles, session isolation, configurable browser settings, and usage controls. Gemini and your application still own the model decision and the action policy.

Hosted Chromium is useful when workers run in containers or serverless environments, when multiple jobs need independent sessions, or when operators need to inspect a remote run. It also adds a network connection and a separate session lifecycle to manage. Evaluate startup time, timeouts, session cleanup, and concurrency limits against your workload rather than assuming the hosted browser removes those concerns.

Start with a controlled page and a single approved action. Then add tools, destinations, and permissions only as tests show they are needed. For connection details, use the documentation; for current plans and limits, see pricing.