Using a Browser Session with Playwright

After creating a session with the AgentGo SDK, you can connect Playwright to that session for browser automation. This guide shows how to use your session ID to get a Playwright browser object.

Prerequisites

  1. A session created using the AgentGo SDK (see Create a Browser Session)
  2. Playwright installed: npm i playwright-core

Connecting Playwright to Your Session

Here’s how to use a session ID to get a Playwright browser object:

import { AgentGo } from '@agentgo-dev/sdk';
import { chromium } from 'playwright-core';

// Initialize SDK client
const client = new AgentGo({
  apiKey: 'your_api_key_here',
});

// Create a session
const session = await client.sessions.create({
  region: 'us'                    // Use lowercase region code
});

// Connect Playwright to the session
const options = {
  _apikey: 'your_api_key_here',
  _sessionId: session.id,         // Use the session ID from SDK
  _region: 'us',                  // Match the session region (lowercase)
  _disable_proxy: false           // Enable proxy (recommended)
};

// Encode options and create connection URL
const urlOptionValue = encodeURIComponent(JSON.stringify(options));
const serverUrl = 'wss://app.browsers.live?launch-options=' + urlOptionValue;

// Connect to the browser session
const browser = await chromium.connect(serverUrl);

Connection Options

When connecting Playwright to your session, you can use these options:

OptionDescriptionRequiredDefault
_apikeyYour AgentGo API keyYesNone
_sessionIdSession ID from SDKNoAuto-generated
_regionGeographic region code (lowercase)No”us”
_disable_proxyDisable proxy usageNofalse

Complete Integration Example

import { AgentGo } from '@agentgo-dev/sdk';
import { chromium } from 'playwright-core';

async function automateWithSession() {
  // Step 1: Create SDK client
  const client = new AgentGo({
    apiKey: 'your_api_key_here',
  });

  // Step 2: Create a session
  const session = await client.sessions.create({
    region: 'us'                    // Can use any supported region: us, uk, de, jp, etc.
  });

  console.log('Session created:', session.id);

  // Step 3: Connect Playwright to the session
  const options = {
    _apikey: 'your_api_key_here',
    _sessionId: session.id,
    _region: 'us',                  // Match the session region (lowercase)
    _disable_proxy: false
  };

  const urlOptionValue = encodeURIComponent(JSON.stringify(options));
  const serverUrl = 'wss://app.browsers.live?launch-options=' + urlOptionValue;
  
  const browser = await chromium.connect(serverUrl);

  // Step 4: Use the browser for automation
  const page = await browser.newPage();
  await page.goto('https://example.com');
  
  // Perform automation tasks
  await page.fill('#search', 'AgentGo');
  await page.press('#search', 'Enter');
  await page.waitForSelector('.results');
  
  // Take a screenshot
  await page.screenshot({ path: 'example.png' });

  // Step 5: Clean up
  await browser.close();
  
  // Optional: Check session status
  const sessionDetails = await client.sessions.retrieve(session.id);
  console.log('Final session status:', sessionDetails.status);
}

automateWithSession().catch(console.error);

Reusing Existing Sessions

You can also connect to existing sessions by their ID:

// Connect to an existing session
const existingSessionId = 'session-abc123';

const options = {
  _apikey: 'your_api_key_here',
  _sessionId: existingSessionId,  // Use existing session ID
  _region: 'us'                   // Use lowercase region code
};

const urlOptionValue = encodeURIComponent(JSON.stringify(options));
const serverUrl = 'wss://app.browsers.live?launch-options=' + urlOptionValue;
const browser = await chromium.connect(serverUrl);

Session Status Monitoring

Monitor your session during automation:

// Check session status periodically
async function monitorSession(client, sessionId) {
  const details = await client.sessions.retrieve(sessionId);
  console.log(`Session ${sessionId} status: ${details.status}`);
  return details;
}

// Use during automation
const sessionStatus = await monitorSession(client, session.id);
if (sessionStatus.status === 'RUNNING') {
  // Continue automation
  await page.goto('https://another-site.com');
}

Common Playwright Operations

Once connected, use standard Playwright operations:

// Navigate and interact
await page.goto('https://example.com');
await page.click('#button');
await page.fill('input[name="username"]', 'myuser');
await page.selectOption('select[name="country"]', 'US');

// Wait for elements
await page.waitForSelector('.loading', { state: 'hidden' });
await page.waitForLoadState('networkidle');

// Extract data
const title = await page.textContent('h1');
const links = await page.$$eval('a', els => els.map(el => el.href));

// Take screenshots
await page.screenshot({ path: 'screenshot.png', fullPage: true });

Error Handling

Handle connection and automation errors:

try {
  const browser = await chromium.connect(serverUrl);
  const page = await browser.newPage();
  
  await page.goto('https://example.com');
  
} catch (error) {
  console.error('Connection or automation failed:', error);
  
  // Check session status for debugging
  const sessionDetails = await client.sessions.retrieve(session.id);
  console.log('Session status:', sessionDetails.status);
}

Region Examples

You can create sessions in different regions based on your target audience or compliance requirements:

// North America
const usSession = await client.sessions.create({ region: 'us' });
const caSession = await client.sessions.create({ region: 'ca' });

// Europe
const ukSession = await client.sessions.create({ region: 'uk' });
const deSession = await client.sessions.create({ region: 'de' });
const frSession = await client.sessions.create({ region: 'fr' });

// Asia
const jpSession = await client.sessions.create({ region: 'jp' });
const sgSession = await client.sessions.create({ region: 'sg' });
const inSession = await client.sessions.create({ region: 'in' });

// Oceania
const auSession = await client.sessions.create({ region: 'au' });

See the Create Browser Session guide for the complete list of supported regions.

Best Practices

  1. Always specify _sessionId when you have a specific session to use
  2. Match regions between SDK session creation and Playwright connection
  3. Choose regions close to your target websites for better performance
  4. Monitor session status during long-running automations
  5. Close browser connections to free up resources

Session Limitations

  • Maximum of 4 concurrent pages per browser session
  • File upload/download operations are not supported
  • Sessions timeout after 120 seconds of inactivity
  • Use appropriate waiting strategies instead of fixed timeouts