Skip to content

Using a browser session

Learn how to connect to and interact with browser sessions

Updated View as Markdown

Connecting to a session

Once you create a session, you’ll receive a connection URL to use with your preferred automation framework. Here’s how to connect:

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];
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];
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);
};
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]
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 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:

const context = browser.contexts()[0];
const page = context.pages()[0];
const page = (await browser.pages())[0];
// Uses default context automatically
context = browser.contexts[0]
page = context.pages[0]
# 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.

Browsers features

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

Live view

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

Session Inspector

The Session Inspector 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 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.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close