---
title: "Using a browser session"
description: "Learn how to connect to and interact with browser sessions"
image: "https://help.agent.mq/og.svg"
---

> Documentation Index
> Fetch the complete documentation index at: https://help.agent.mq/llms.txt
> Use this file to discover all available pages before exploring further.

# Using a browser session

## Connecting to a session

Once you [create a session](/browsers/getting-started/create-browser-session), you'll receive a connection URL to use with your preferred automation framework. Here's how to connect:

### Node.js

```javascript Playwright
  import { chromium } from "playwright-core";
  import { Browsers } from "@agentmq/browsers";

  const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN });

  // Create a session
  const session = await browsers.sessions.create();

  const browser = await chromium.connectOverCDP(session.connectUrl);

  // Use the default context and page
  const context = browser.contexts()[0];
  const page = context.pages()[0];
```

```javascript Puppeteer
  import puppeteer from "puppeteer-core";
  import { Browsers } from "@agentmq/browsers";

  const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN });

  // Create a session
  const session = await browsers.sessions.create();

  const browser = await puppeteer.connect({
    browserWSEndpoint: session.connectUrl
  });

  // Use the default page
  const page = (await browser.pages())[0];
```

```javascript Selenium
  import { Builder } from 'selenium-webdriver';
  import { Options } from 'selenium-webdriver/chrome';
  import { Browsers } from "@agentmq/browsers";

  class BrowsersConnection {
    constructor(sessionId) {
      this.sessionId = sessionId;
    }

    getHeaders() {
      return {
        'Authorization: Bearer': process.env.AGENTMQ_TOKEN,
        'session-id': this.sessionId
      };
    }
  }

  // Create a session
  const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN });
  const session = await browsers.sessions.create();

  // Create connection with custom headers
  const connection = new BrowsersConnection(session.id);

  // Configure WebDriver
  const driver = await new Builder()
    .usingServer(session.seleniumRemoteUrl)
    .setChromeOptions(new Options())
    .build();

  // Add custom headers to all requests
  const originalExecute = driver.executor_.execute.bind(driver.executor_);
  driver.executor_.execute = async function (command) {
    command.headers = { ...command.headers, ...connection.getHeaders() };
    return originalExecute(command);
  };
```

### Python

```python Playwright
  import os
  from playwright.sync_api import sync_playwright
  from agentmq.browsers import Browsers

  # Create a session
  browsers = Browsers(api_key=os.environ["AGENTMQ_TOKEN"])
  session = browsers.sessions.create()

  with sync_playwright() as playwright:
      browser = playwright.chromium.connect_over_cdp(session.connect_url)

      # Use the default context and page
      context = browser.contexts[0]
      page = context.pages[0]
```

```python Selenium
  import os
  from selenium import webdriver
  from selenium.webdriver.remote.webdriver import WebDriver
  from selenium.webdriver.remote.remote_connection import RemoteConnection
  from agentmq.browsers import Browsers

  class BrowsersConnection(RemoteConnection):
      """Manage a single session with Browsers."""

      def __init__(self, session_id, *args, **kwargs):
          self.session_id = session_id
          super().__init__(*args, **kwargs)

      def get_remote_connection_headers(self, parsed_url, keep_alive=False):
          headers = super().get_remote_connection_headers(parsed_url, keep_alive)
          headers.update({
              "Authorization": os.environ["AGENTMQ_TOKEN"],
              "session-id": self.session_id,
          })
          return headers

  # Create a session
  browsers = Browsers(api_key=os.environ["AGENTMQ_TOKEN"])
  session = browsers.sessions.create()

  # Connect using custom connection class
  connection = BrowsersConnection(
      session.id,
      session.selenium_remote_url
  )
  driver = webdriver.Remote(
      command_executor=connection,
      options=webdriver.ChromeOptions()
  )
```

### Connection best practices

1. **Connection timeout**: You have 5 minutes to connect to a newly created session before it terminates. To prevent timeouts:

   * Connect promptly after creation
   * Enable [keep alive](/browsers/long-sessions/overview) for sessions that need to persist
   * Use the connection URL immediately after receiving it

2. **Use default context**: Always use the default context and page when possible so that the session's managed identity features behave as expected:

### Node.js

```typescript Playwright
  const context = browser.contexts()[0];
  const page = context.pages()[0];
```

```typescript Puppeteer
  const page = (await browser.pages())[0];
```

```typescript Selenium
  // Uses default context automatically
```

### Python

```python Playwright
  context = browser.contexts[0]
  page = context.pages[0]
```

```python Selenium
  # Uses default context automatically
```

## Controlling the browser

Once connected, use your preferred framework's APIs to control the browser. Each framework has its own methods for navigation, interaction, and automation.

- **Stagehand** — [Build reliable browser automation with AI-powered element selection and self-healing scripts](https://docs.stagehand.dev/)

- **Playwright** — [Create fast, reliable end-to-end tests with built-in auto-waiting and mobile
emulation](https://playwright.dev/)

- **Puppeteer** — [Headless Chrome automation with a lightweight API and strong DevTools
integration](https://pptr.dev/)

- **Selenium** — [Industry-standard testing framework supporting all major browsers and programming languages](https://www.selenium.dev)

### Browsers features

When running browsers in the cloud, certain operations require special handling through the Browsers APIs:

- **File downloads** — [Securely retrieve files from your cloud browser session](/browsers/files/downloads)

- **Screenshots** — [Capture high-quality browser screenshots with custom settings](/browsers/files/screenshots)

- **PDF generation** — [Create PDFs with advanced formatting options](/browsers/files/pdfs)

- **File upload** — [Transfer files directly to your browser session](/browsers/files/uploads)

### Live view

Live view gives you real-time visibility into your browser sessions through two interfaces:

#### Session Inspector

The [Session Inspector](/browsers/observability/observability) provides real-time debugging:

Monitor your session's activity with:

* Live browser state and interactions
* Real-time network requests and responses
* Console output and error tracking
* Performance metrics and resource usage
* Session replay

#### Embedded view

Integrate the [Live View](/browsers/observability/session-live-view) directly into your application to show your users their automated browser sessions in real-time. The Live View enables remote control over the browser, unlocking human-in-the-loop possibilities to handle authentication, CAPTCHAs, or unexpected errors.

## Ending your session

Browsers automatically handles session termination when you disconnect. For details about termination, timeouts, and lifecycle management best practices, see [Manage a browser session](/browsers/getting-started/manage-browser-session).

Source: https://help.agent.mq/browsers/getting-started/using-browser-session/index.mdx
