A high-level API to automate Chromium
npx @tessl/cli install tessl/npm-playwright-chromium@1.55.0Playwright Chromium provides a high-level API to automate Chromium browsers for end-to-end testing, web scraping, and browser automation. It offers a focused, Chromium-specific subset of the full Playwright framework with comprehensive features for modern web application testing and automation.
npm install playwright-chromiumimport { chromium, devices, errors } from "playwright-chromium";For CommonJS:
const { chromium, devices, errors } = require("playwright-chromium");import { chromium } from "playwright-chromium";
// Launch Chromium browser
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
// Navigate and interact
await page.goto("https://example.com");
await page.fill("input[name='search']", "playwright");
await page.click("button[type='submit']");
// Capture screenshot
await page.screenshot({ path: "screenshot.png" });
// Cleanup
await browser.close();Playwright Chromium is built around several key components:
BrowserType for launching and connecting to Chromium browsersBrowserContext provides isolated sessions with independent cookies, storage, and permissionsPage interface for navigating, interacting with elements, and executing JavaScriptElementHandle for direct DOM references and Locator for modern auto-waiting patternsCore browser lifecycle management including launching Chromium instances, creating contexts, and managing browser connections.
interface BrowserType {
launch(options?: LaunchOptions): Promise<Browser>;
connect(wsEndpoint: string, options?: ConnectOptions): Promise<Browser>;
connectOverCDP(endpointURL: string, options?: ConnectOverCDPOptions): Promise<Browser>;
executablePath(): string;
name(): string;
}
interface Browser {
newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
contexts(): BrowserContext[];
close(): Promise<void>;
isConnected(): boolean;
version(): string;
}Comprehensive page automation including navigation, element interaction, JavaScript execution, and content manipulation.
interface Page {
goto(url: string, options?: PageGotoOptions): Promise<Response | null>;
click(selector: string, options?: PageClickOptions): Promise<void>;
fill(selector: string, value: string, options?: PageFillOptions): Promise<void>;
type(selector: string, text: string, options?: PageTypeOptions): Promise<void>;
screenshot(options?: PageScreenshotOptions): Promise<Buffer>;
evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg?: Arg): Promise<R>;
waitForSelector(selector: string, options?: PageWaitForSelectorOptions): Promise<ElementHandle | null>;
}Modern element interaction API with auto-waiting capabilities and comprehensive element state checking.
interface Locator {
click(options?: LocatorClickOptions): Promise<void>;
fill(value: string, options?: LocatorFillOptions): Promise<void>;
textContent(options?: LocatorTextContentOptions): Promise<string | null>;
isVisible(options?: LocatorIsVisibleOptions): Promise<boolean>;
waitFor(options?: LocatorWaitForOptions): Promise<void>;
locator(selector: string): Locator;
count(): Promise<number>;
}
interface ElementHandle {
click(options?: ElementHandleClickOptions): Promise<void>;
fill(value: string, options?: ElementHandleFillOptions): Promise<void>;
textContent(): Promise<string | null>;
getAttribute(name: string): Promise<string | null>;
boundingBox(): Promise<{ x: number; y: number; width: number; height: number; } | null>;
}Request and response interception, network monitoring, and request routing capabilities for testing and automation.
interface Request {
url(): string;
method(): string;
headers(): { [key: string]: string; };
postData(): string | null;
response(): Promise<Response | null>;
frame(): Frame;
}
interface Response {
url(): string;
status(): number;
headers(): { [key: string]: string; };
json(): Promise<any>;
text(): Promise<string>;
body(): Promise<Buffer>;
}
interface Route {
fulfill(response: RouteFullfillResponse): Promise<void>;
continue(overrides?: RouteContinueOverrides): Promise<void>;
abort(errorCode?: string): Promise<void>;
}Comprehensive input simulation including keyboard, mouse, and touch interactions for realistic user behavior testing.
interface Keyboard {
down(key: string, options?: KeyboardDownOptions): Promise<void>;
up(key: string): Promise<void>;
press(key: string, options?: KeyboardPressOptions): Promise<void>;
type(text: string, options?: KeyboardTypeOptions): Promise<void>;
}
interface Mouse {
move(x: number, y: number, options?: MouseMoveOptions): Promise<void>;
click(x: number, y: number, options?: MouseClickOptions): Promise<void>;
down(options?: MouseDownOptions): Promise<void>;
up(options?: MouseUpOptions): Promise<void>;
}HTTP API testing capabilities with request/response handling, authentication, and context management.
interface APIRequest {
newContext(options?: APIRequestNewContextOptions): Promise<APIRequestContext>;
get(url: string, options?: APIRequestGetOptions): Promise<APIResponse>;
post(url: string, options?: APIRequestPostOptions): Promise<APIResponse>;
put(url: string, options?: APIRequestPutOptions): Promise<APIResponse>;
delete(url: string, options?: APIRequestDeleteOptions): Promise<APIResponse>;
}
interface APIResponse {
url(): string;
status(): number;
headers(): { [key: string]: string; };
json(): Promise<any>;
text(): Promise<string>;
ok(): boolean;
}/** Chromium browser type - primary interface for Chromium automation */
const chromium: BrowserType;
/** Firefox browser type - available but not the primary focus */
const firefox: BrowserType;
/** WebKit browser type - available but not the primary focus */
const webkit: BrowserType;/** HTTP API testing capabilities */
const request: APIRequest;
/** Custom selector engine management */
const selectors: Selectors;
/** Collection of predefined device configurations */
const devices: { [deviceName: string]: DeviceDescriptor; };
/** Error classes for exception handling */
const errors: { TimeoutError: typeof TimeoutError; };⚠️ Warning: Experimental features are subject to change and may be unstable
/** Electron application automation (experimental) */
const _electron: Electron;
/** Android device automation (experimental) */
const _android: Android;
/** Experimental BiDi Chromium support */
const _bidiChromium: BrowserType;
/** Experimental BiDi Firefox support */
const _bidiFirefox: BrowserType;interface LaunchOptions {
headless?: boolean | 'new';
slowMo?: number;
timeout?: number;
channel?: string;
executablePath?: string;
args?: string[];
proxy?: { server: string; bypass?: string; username?: string; password?: string; };
downloadsPath?: string;
chromiumSandbox?: boolean;
handleSIGINT?: boolean;
handleSIGTERM?: boolean;
handleSIGHUP?: boolean;
logger?: Logger;
env?: { [key: string]: string | number | boolean; };
}
interface BrowserContextOptions {
/** Whether to automatically download all the attachments. Defaults to `true`. */
acceptDownloads?: boolean;
/** Base URL for relative navigation. */
baseURL?: string;
/** Toggles bypassing page's Content-Security-Policy. Defaults to `false`. */
bypassCSP?: boolean;
/** Emulates `prefers-colors-scheme` media feature. Defaults to `'light'`. */
colorScheme?: null | 'light' | 'dark' | 'no-preference';
/** Specify device scale factor (can be thought of as dpr). Defaults to `1`. */
deviceScaleFactor?: number;
/** An object containing additional HTTP headers to be sent with every request. */
extraHTTPHeaders?: { [key: string]: string; };
/** Emulates `'forced-colors'` media feature. Defaults to `'none'`. */
forcedColors?: null | 'active' | 'none';
/** Geolocation data. */
geolocation?: { latitude: number; longitude: number; accuracy?: number; };
/** Specifies if viewport supports touch events. Defaults to false. */
hasTouch?: boolean;
/** Credentials for HTTP authentication. */
httpCredentials?: { username: string; password: string; };
/** Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. */
ignoreHTTPSErrors?: boolean;
/** Whether the `meta viewport` tag is taken into account. Defaults to `false`. */
isMobile?: boolean;
/** Whether or not to enable JavaScript in the context. Defaults to `true`. */
javaScriptEnabled?: boolean;
/** Specify user locale, for example `en-GB`, `de-DE`, etc. */
locale?: string;
/** Logger sink for Playwright logging. */
logger?: Logger;
/** Whether to emulate network being offline. Defaults to `false`. */
offline?: boolean;
/** A list of permissions to grant to all pages in this context. */
permissions?: string[];
/** Network proxy settings to use with this context. */
proxy?: { server: string; bypass?: string; username?: string; password?: string; };
/** Enables HAR recording for all pages into the specified path. */
recordHar?: RecordHarOptions;
/** Enables video recording for all pages into the specified directory. */
recordVideo?: RecordVideoOptions;
/** Emulates `'prefers-reduced-motion'` media feature. Defaults to `'no-preference'`. */
reducedMotion?: null | 'reduce' | 'no-preference';
/** Emulates consistent window screen size available inside web page via `window.screen`. */
screen?: { width: number; height: number; };
/** Changes the timezone of the context. */
timezoneId?: string;
/** Specific user agent to use in this context. */
userAgent?: string;
/** Emulates consistent viewport for each page. */
viewport?: null | { width: number; height: number; };
}
interface RecordHarOptions {
/** Whether to omit content. */
omitContent?: boolean;
/** Content mode: 'omit', 'embed', or 'attach'. */
content?: 'omit' | 'embed' | 'attach';
/** Path to save the HAR file. */
path: string;
/** Recording mode: 'full' or 'minimal'. */
mode?: 'full' | 'minimal';
/** URL filter pattern. */
urlFilter?: string | RegExp;
}
interface RecordVideoOptions {
/** Directory to save video files. */
dir: string;
/** Video frame size. */
size?: { width: number; height: number; };
}
interface ConnectOptions {
/** Additional headers to send to the browser. */
headers?: { [key: string]: string; };
/** Slows down Playwright operations by the specified amount of milliseconds. */
slowMo?: number;
/** Logger sink for Playwright logging. */
logger?: Logger;
/** Maximum time in milliseconds to wait for the connection to be established. */
timeout?: number;
}
interface ConnectOverCDPOptions {
/** Browser websocket endpoint to connect to. */
wsEndpoint?: string;
/** Additional headers to send to the browser. */
headers?: { [key: string]: string; };
/** Slows down Playwright operations by the specified amount of milliseconds. */
slowMo?: number;
/** Logger sink for Playwright logging. */
logger?: Logger;
/** Maximum time in milliseconds to wait for the connection to be established. */
timeout?: number;
}
interface Logger {
/** Determines whether sink is interested in the logger with the given name and severity. */
isEnabled(name: string, severity: 'verbose' | 'info' | 'warning' | 'error'): boolean;
/** Log a message. */
log(name: string, severity: 'verbose' | 'info' | 'warning' | 'error', message: string | Error, args: ReadonlyArray<Object>, hints: { color?: string; }): void;
}
interface DeviceDescriptor {
/** User agent string. */
userAgent: string;
/** Viewport dimensions. */
viewport: { width: number; height: number; };
/** Device scale factor. */
deviceScaleFactor: number;
/** Whether device supports touch. */
isMobile: boolean;
/** Whether device has touch support. */
hasTouch: boolean;
/** Default browser to run on this device. */
defaultBrowserType?: 'chromium' | 'firefox' | 'webkit';
}
interface PageGotoOptions {
/** Referer header value. */
referer?: string;
/** Maximum operation time in milliseconds. Defaults to `0` - no timeout. */
timeout?: number;
/** When to consider operation succeeded, defaults to `load`. */
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit';
}
interface PageScreenshotOptions {
/** An image format. Defaults to 'png'. */
type?: 'png' | 'jpeg';
/** The file path to save the image to. */
path?: string;
/** The quality of the image, between 0-100. Not applicable to png images. */
quality?: number;
/** When true, takes a screenshot of the full scrollable page. Defaults to `false`. */
fullPage?: boolean;
/** An object which specifies clipping region of the page. */
clip?: { x: number; y: number; width: number; height: number; };
/** Hides default white background and allows capturing screenshots with transparency. */
omitBackground?: boolean;
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
timeout?: number;
/** Caret color in CSS format. */
caret?: 'hide' | 'initial';
/** When set to `disabled`, screenshot will have scale set to 1. */
scale?: 'css' | 'device';
}
interface PageClickOptions {
/** Defaults to `left`. */
button?: 'left' | 'right' | 'middle';
/** defaults to 1. See [UIEvent.detail]. */
clickCount?: number;
/** Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0. */
delay?: number;
/** Whether to bypass the actionability checks. Defaults to `false`. */
force?: boolean;
/** Modifier keys to press. */
modifiers?: Array<'Alt' | 'Control' | 'ControlOrMeta' | 'Meta' | 'Shift'>;
/** Actions that initiate navigations are waiting for these navigations to happen. */
noWaitAfter?: boolean;
/** A point to use relative to the top-left corner of element padding box. */
position?: { x: number; y: number; };
/** When true, the call requires selector to resolve to a single element. */
strict?: boolean;
/** Maximum time in milliseconds. */
timeout?: number;
}
interface PageFillOptions {
/** Whether to bypass the actionability checks. Defaults to `false`. */
force?: boolean;
/** This option has no effect. */
noWaitAfter?: boolean;
/** When true, the call requires selector to resolve to a single element. */
strict?: boolean;
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
timeout?: number;
}
interface PageTypeOptions {
/** Time to wait between key presses in milliseconds. Defaults to 0. */
delay?: number;
/** Actions that initiate navigations are waiting for these navigations to happen. */
noWaitAfter?: boolean;
/** When true, the call requires selector to resolve to a single element. */
strict?: boolean;
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
timeout?: number;
}
interface PageWaitForSelectorOptions {
/** Defaults to `'visible'`. */
state?: 'attached' | 'detached' | 'visible' | 'hidden';
/** When true, the call requires selector to resolve to a single element. */
strict?: boolean;
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
timeout?: number;
}
interface PageFunction<Arg, R> {
/** Function to be evaluated in the page context. */
(arg: Arg): R | Promise<R>;
}
interface RouteFullfillResponse {
/** Response status code, defaults to `200`. */
status?: number;
/** Response headers. */
headers?: { [key: string]: string; };
/** Response body. */
body?: string | Buffer;
/** If set, equals to setting `Content-Type` response header. */
contentType?: string;
/** Response path for file-based response. */
path?: string;
}
interface RouteContinueOverrides {
/** HTTP headers to append to the original request. */
headers?: { [key: string]: string; };
/** HTTP method for the request. */
method?: string;
/** Post data for the request. */
postData?: string | Buffer;
/** Request URL. */
url?: string;
}
interface CDPSession {
/** Send a CDP command. */
send<T extends keyof Protocol.CommandParameters>(
method: T,
params?: Protocol.CommandParameters[T]
): Promise<Protocol.CommandReturnValues[T]>;
/** Detaches the CDPSession from the target. */
detach(): Promise<void>;
}
interface Frame {
/** Returns the return value of pageFunction. */
evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>;
evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>;
/** Returns the return value of pageFunction invocation as a JSHandle. */
evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>;
/** Returns the URL of the frame. */
url(): string;
/** Returns the page containing this frame. */
page(): Page;
/** Returns the parent frame, if any. Detached frames and main frames return null. */
parentFrame(): Frame | null;
/** Returns the array of child frames. */
childFrames(): Frame[];
}
interface Worker {
/** Returns the return value of pageFunction. */
evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>;
evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>;
/** Returns the return value of pageFunction invocation as a JSHandle. */
evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>;
/** Returns the URL of the worker. */
url(): string;
}
interface Selectors {
/** Register a custom selector engine. */
register(name: string, script: string): Promise<void>;
/** Set the default selector engine. */
setTestIdAttribute(attributeName: string): void;
}
interface SmartHandle<T> {
/** JSHandle for any object, ElementHandle for DOM nodes. */
}
interface JSHandle<T = any> {
/** Returns the return value of pageFunction. */
evaluate<R, Arg>(pageFunction: PageFunctionOn<T, Arg, R>, arg: Arg): Promise<R>;
evaluate<R>(pageFunction: PageFunctionOn<T, void, R>, arg?: any): Promise<R>;
/** Returns the return value of pageFunction invocation as a JSHandle. */
evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<T, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
evaluateHandle<R>(pageFunction: PageFunctionOn<T, void, R>, arg?: any): Promise<SmartHandle<R>>;
/** The JSHandle.dispose method stops referencing the element handle. */
dispose(): Promise<void>;
}
interface Page {
/** The page's main frame. */
mainFrame(): Frame;
/** An array of all frames attached to the page. */
frames(): Frame[];
/** All of the dedicated WebWorkers associated with the page. */
workers(): Worker[];
}
interface ElementHandle<T=Node> extends JSHandle<T> {
/** The ElementHandle.ownerFrame method returns the frame containing the element. */
ownerFrame(): Promise<Frame | null>;
}
type PageFunctionOn<On, Arg2, R> = string | ((on: On, arg2: Arg2) => R | Promise<R>);