/
Using the browser

Using the browser

Each computer includes a browser that can be used to navigate websites, interact with web applications, perform web scraping, and more. In this guide, we'll walk through how to connect to the computer's browser, and use it with libraries like Playwright and Puppeteer.


Connect to the browser

To connect to the browser, you can use the browser.connect method. This will return a CDP URL that you can use with libraries like Playwright and Puppeteer to automate web tasks.

import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
// Wait for computer to start
await computer.waitForState("started");
// Connect to the browser
const handle = await computer.browser.connect();
// Use this URL with Playwright and Puppeteer
console.log(handle.cdpUrl);

Usage with Playwright

Playwright is a popular library for browser automation. It provides a high-level API to control the browser. Use the CDP URL returned from the browser.connect method to connect Playwright to the browser.

import { Computer } from "@metallichq/sdk";
import { chromium } from 'playwright-core';
// Start computer
const computer = await Computer.start("your-computer-id");
// Wait for computer to start
await computer.waitForState("started");
// Connect to the browser
const handle = await computer.browser.connect();
// Pass the CDP URL to Playwright
const browser = await chromium.connectOverCDP(handle.cdpUrl);
// Run your automation
const context = browser.contexts()[0];
const page = await context.pages()[0];
await page.goto("https://news.ycombinator.com");

Usage with Puppeteer

Puppeteer is a popular library for browser automation. It provides a high-level API to control the browser. Use the CDP URL returned from the browser.connect method to connect Puppeteer to the browser.

import { Computer } from "@metallichq/sdk";
import puppeteer from 'puppeteer-core';
// Start computer
const computer = await Computer.start("your-computer-id");
// Wait for computer to start
await computer.waitForState("started");
// Connect to the browser
const handle = await computer.browser.connect();
// Use this URL with Puppeteer
const browser = await puppeteer.connect({
browserURL: handle.cdpUrl
});
// Run your automation
const page = await browser.newPage();
await page.goto("https://news.ycombinator.com");