CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-playwright-chromium

A high-level API to automate Chromium

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

browser-management.mddocs/

Browser Management

Core browser lifecycle management for launching Chromium instances, creating isolated contexts, and managing browser connections.

Capabilities

Browser Type

Main entry point for browser operations including launching new instances and connecting to existing ones.

/**
 * Browser type interface providing methods to launch and connect to browsers
 */
interface BrowserType {
  /** Launch a new browser instance */
  launch(options?: LaunchOptions): Promise<Browser>;
  /** Connect to an existing browser via WebSocket */
  connect(wsEndpoint: string, options?: ConnectOptions): Promise<Browser>;
  /** Connect to an existing browser via Chrome DevTools Protocol */
  connectOverCDP(endpointURL: string, options?: ConnectOverCDPOptions): Promise<Browser>;
  /** Get the executable path for the browser */
  executablePath(): string;
  /** Get the browser type name */
  name(): string;
}

Usage Examples:

import { chromium } from "playwright-chromium";

// Launch browser with custom options
const browser = await chromium.launch({
  headless: false,
  slowMo: 100,
  args: ['--start-maximized']
});

// Connect to existing browser
const browser = await chromium.connect('ws://localhost:9222/devtools/browser');

// Connect via CDP
const browser = await chromium.connectOverCDP('http://localhost:9222');

Browser Instance

Represents a browser instance with methods for creating contexts and managing the browser lifecycle.

/**
 * Browser instance providing context management and lifecycle control
 */
interface Browser {
  /** Create a new browser context */
  newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
  /** Get all browser contexts */
  contexts(): BrowserContext[];
  /** Close the browser instance */
  close(): Promise<void>;
  /** Check if browser is connected */
  isConnected(): boolean;
  /** Get browser version string */
  version(): string;
  /** Get the browser type */
  browserType(): BrowserType;
  /** Create a new CDP session */
  newBrowserCDPSession(): Promise<CDPSession>;
  /** Start tracing */
  startTracing(page?: Page, options?: TracingStartOptions): Promise<void>;
  /** Stop tracing */
  stopTracing(): Promise<Buffer>;
}

Usage Examples:

// Create multiple contexts for isolation
const browser = await chromium.launch();
const context1 = await browser.newContext({ viewport: { width: 1920, height: 1080 } });
const context2 = await browser.newContext({ viewport: { width: 375, height: 667 } });

// Check browser state
console.log(`Browser version: ${browser.version()}`);
console.log(`Connected: ${browser.isConnected()}`);
console.log(`Active contexts: ${browser.contexts().length}`);

// Cleanup
await browser.close();

Browser Context

Isolated browser session providing independent cookies, storage, permissions, and page management.

/**
 * Browser context providing isolated browsing session
 */
interface BrowserContext {
  /** Create a new page in this context */
  newPage(): Promise<Page>;
  /** Get all pages in this context */
  pages(): Page[];
  /** Close this context and all its pages */
  close(): Promise<void>;
  /** Get cookies from this context */
  cookies(urls?: string | string[]): Promise<Cookie[]>;
  /** Add cookies to this context */
  addCookies(cookies: Cookie[]): Promise<void>;
  /** Clear all cookies in this context */
  clearCookies(): Promise<void>;
  /** Grant permissions to this context */
  grantPermissions(permissions: string[], options?: GrantPermissionsOptions): Promise<void>;
  /** Clear all granted permissions */
  clearPermissions(): Promise<void>;
  /** Set geolocation for this context */
  setGeolocation(geolocation: Geolocation | null): Promise<void>;
  /** Set extra HTTP headers for all requests */
  setExtraHTTPHeaders(headers: { [key: string]: string; }): Promise<void>;
  /** Set HTTP credentials for this context */
  setHTTPCredentials(httpCredentials: HTTPCredentials | null): Promise<void>;
  /** Add initialization script to run on every page */
  addInitScript(script: Function | string | { path?: string; content?: string; }, arg?: any): Promise<void>;
  /** Expose a binding for pages to call */
  exposeBinding(name: string, callback: BindingCallback, options?: ExposeBindingOptions): Promise<void>;
  /** Expose a function for pages to call */
  exposeFunction(name: string, callback: Function): Promise<void>;
  /** Route requests matching URL pattern */
  route(url: string | RegExp | ((url: URL) => boolean), handler: RouteHandler): Promise<void>;
  /** Route requests using HAR file */
  routeFromHAR(har: string, options?: RouteFromHAROptions): Promise<void>;
  /** Remove request routing */
  unroute(url: string | RegExp | ((url: URL) => boolean), handler?: RouteHandler): Promise<void>;
  /** Get or save storage state */
  storageState(options?: StorageStateOptions): Promise<StorageState>;
  /** Wait for an event */
  waitForEvent(event: string, optionsOrPredicate?: WaitForEventOptions | Function): Promise<any>;
  /** Get the browser instance */
  browser(): Browser | null;
  /** Get background pages (Service Workers) */
  backgroundPages(): Page[];
  /** Get service workers */
  serviceWorkers(): Worker[];
}

Usage Examples:

// Create context with mobile device simulation
const context = await browser.newContext({
  viewport: { width: 375, height: 667 },
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',
  isMobile: true,
  hasTouch: true
});

// Set up context-wide configurations
await context.setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
await context.grantPermissions(['geolocation']);
await context.addCookies([
  { name: 'session', value: 'abc123', domain: 'example.com', path: '/' }
]);

// Route all API calls
await context.route('**/api/**', route => {
  route.fulfill({
    status: 200,
    body: JSON.stringify({ mocked: true })
  });
});

// Multiple pages in same context share state
const page1 = await context.newPage();
const page2 = await context.newPage();

Configuration Types

Launch Options

interface LaunchOptions {
  /** Whether to run browser in headless mode */
  headless?: boolean | 'new';
  /** Slow down operations by specified milliseconds */
  slowMo?: number;
  /** Maximum time in milliseconds to wait for browser to start */
  timeout?: number;
  /** Browser distribution channel */
  channel?: string;
  /** Path to browser executable */
  executablePath?: string;
  /** Additional arguments to pass to browser */
  args?: string[];
  /** Network proxy settings */
  proxy?: ProxySettings;
  /** Path to directory for downloads */
  downloadsPath?: string;
  /** Enable/disable Chromium sandbox */
  chromiumSandbox?: boolean;
  /** Whether Playwright should handle SIGINT */
  handleSIGINT?: boolean;
  /** Whether Playwright should handle SIGTERM */
  handleSIGTERM?: boolean;
  /** Whether Playwright should handle SIGHUP */
  handleSIGHUP?: boolean;
  /** Logger instance for debugging */
  logger?: Logger;
  /** Environment variables */
  env?: { [key: string]: string | number | boolean; };
}

Connection Options

interface ConnectOptions {
  /** Maximum time to wait for connection */
  timeout?: number;
  /** Slow down operations by specified milliseconds */
  slowMo?: number;
  /** Logger instance for debugging */
  logger?: Logger;
  /** Additional headers for WebSocket connection */
  headers?: { [key: string]: string; };
}

interface ConnectOverCDPOptions {
  /** Maximum time to wait for connection */
  timeout?: number;
  /** Slow down operations by specified milliseconds */
  slowMo?: number;
  /** Logger instance for debugging */
  logger?: Logger;
  /** Endpoint URL for CDP connection */
  endpointURL: string;
}

Context Options

interface BrowserContextOptions {
  /** Viewport size, null disables default 1280x720 viewport */
  viewport?: ViewportSize | null;
  /** Screen size for window.screen */
  screen?: ScreenSize;
  /** Disable default viewport */
  noViewport?: boolean;
  /** Whether to ignore HTTPS errors */
  ignoreHTTPSErrors?: boolean;
  /** Whether JavaScript is enabled */
  javaScriptEnabled?: boolean;
  /** Whether to bypass CSP */
  bypassCSP?: boolean;
  /** User agent string */
  userAgent?: string;
  /** Locale identifier */
  locale?: string;
  /** Timezone identifier */
  timezoneId?: string;
  /** Geolocation settings */
  geolocation?: Geolocation;
  /** Permissions to grant */
  permissions?: string[];
  /** Extra HTTP headers for all requests */
  extraHTTPHeaders?: { [key: string]: string; };
  /** Whether to emulate network offline */
  offline?: boolean;
  /** HTTP authentication credentials */
  httpCredentials?: HTTPCredentials;
  /** Device scale factor */
  deviceScaleFactor?: number;
  /** Whether to simulate mobile device */
  isMobile?: boolean;
  /** Whether device has touch support */
  hasTouch?: boolean;
  /** Color scheme preference */
  colorScheme?: 'light' | 'dark' | 'no-preference' | null;
  /** Reduced motion preference */
  reducedMotion?: 'reduce' | 'no-preference' | null;
  /** Forced colors preference */
  forcedColors?: 'active' | 'none' | null;
  /** Whether to accept downloads */
  acceptDownloads?: boolean;
  /** HAR recording options */
  recordHar?: RecordHarOptions;
  /** Video recording options */
  recordVideo?: RecordVideoOptions;
  /** Proxy settings for this context */
  proxy?: ProxySettings;
}

Utility Types

interface ViewportSize {
  width: number;
  height: number;
}

interface ScreenSize {
  width: number;
  height: number;
}

interface Geolocation {
  latitude: number;
  longitude: number;
  accuracy?: number;
}

interface HTTPCredentials {
  username: string;
  password: string;
}

interface ProxySettings {
  server: string;
  bypass?: string;
  username?: string;
  password?: string;
}

interface Cookie {
  name: string;
  value: string;
  domain?: string;
  path?: string;
  expires?: number;
  httpOnly?: boolean;
  secure?: boolean;
  sameSite?: 'Strict' | 'Lax' | 'None';
}

Install with Tessl CLI

npx tessl i tessl/npm-playwright-chromium

docs

api-testing.md

browser-management.md

element-handling.md

index.md

input-simulation.md

network-control.md

page-interaction.md

tile.json