A high-level API to automate Chromium
npx @tessl/cli install tessl/npm-playwright-chromium@1.55.00
# Playwright Chromium
1
2
Playwright 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.
3
4
## Package Information
5
6
- **Package Name**: playwright-chromium
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install playwright-chromium`
10
11
## Core Imports
12
13
```typescript
14
import { chromium, devices, errors } from "playwright-chromium";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { chromium, devices, errors } = require("playwright-chromium");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { chromium } from "playwright-chromium";
27
28
// Launch Chromium browser
29
const browser = await chromium.launch();
30
const context = await browser.newContext();
31
const page = await context.newPage();
32
33
// Navigate and interact
34
await page.goto("https://example.com");
35
await page.fill("input[name='search']", "playwright");
36
await page.click("button[type='submit']");
37
38
// Capture screenshot
39
await page.screenshot({ path: "screenshot.png" });
40
41
// Cleanup
42
await browser.close();
43
```
44
45
## Architecture
46
47
Playwright Chromium is built around several key components:
48
49
- **Browser Management**: `BrowserType` for launching and connecting to Chromium browsers
50
- **Context Isolation**: `BrowserContext` provides isolated sessions with independent cookies, storage, and permissions
51
- **Page Interaction**: `Page` interface for navigating, interacting with elements, and executing JavaScript
52
- **Element Handling**: Dual API with `ElementHandle` for direct DOM references and `Locator` for modern auto-waiting patterns
53
- **Network Control**: Request/response interception, routing, and monitoring capabilities
54
- **Input Simulation**: Comprehensive keyboard, mouse, and touch input simulation
55
- **API Testing**: Built-in HTTP client for API automation and testing
56
57
## Capabilities
58
59
### Browser Management
60
61
Core browser lifecycle management including launching Chromium instances, creating contexts, and managing browser connections.
62
63
```typescript { .api }
64
interface BrowserType {
65
launch(options?: LaunchOptions): Promise<Browser>;
66
connect(wsEndpoint: string, options?: ConnectOptions): Promise<Browser>;
67
connectOverCDP(endpointURL: string, options?: ConnectOverCDPOptions): Promise<Browser>;
68
executablePath(): string;
69
name(): string;
70
}
71
72
interface Browser {
73
newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
74
contexts(): BrowserContext[];
75
close(): Promise<void>;
76
isConnected(): boolean;
77
version(): string;
78
}
79
```
80
81
[Browser Management](./browser-management.md)
82
83
### Page Interaction
84
85
Comprehensive page automation including navigation, element interaction, JavaScript execution, and content manipulation.
86
87
```typescript { .api }
88
interface Page {
89
goto(url: string, options?: PageGotoOptions): Promise<Response | null>;
90
click(selector: string, options?: PageClickOptions): Promise<void>;
91
fill(selector: string, value: string, options?: PageFillOptions): Promise<void>;
92
type(selector: string, text: string, options?: PageTypeOptions): Promise<void>;
93
screenshot(options?: PageScreenshotOptions): Promise<Buffer>;
94
evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg?: Arg): Promise<R>;
95
waitForSelector(selector: string, options?: PageWaitForSelectorOptions): Promise<ElementHandle | null>;
96
}
97
```
98
99
[Page Interaction](./page-interaction.md)
100
101
### Element Handling
102
103
Modern element interaction API with auto-waiting capabilities and comprehensive element state checking.
104
105
```typescript { .api }
106
interface Locator {
107
click(options?: LocatorClickOptions): Promise<void>;
108
fill(value: string, options?: LocatorFillOptions): Promise<void>;
109
textContent(options?: LocatorTextContentOptions): Promise<string | null>;
110
isVisible(options?: LocatorIsVisibleOptions): Promise<boolean>;
111
waitFor(options?: LocatorWaitForOptions): Promise<void>;
112
locator(selector: string): Locator;
113
count(): Promise<number>;
114
}
115
116
interface ElementHandle {
117
click(options?: ElementHandleClickOptions): Promise<void>;
118
fill(value: string, options?: ElementHandleFillOptions): Promise<void>;
119
textContent(): Promise<string | null>;
120
getAttribute(name: string): Promise<string | null>;
121
boundingBox(): Promise<{ x: number; y: number; width: number; height: number; } | null>;
122
}
123
```
124
125
[Element Handling](./element-handling.md)
126
127
### Network Control
128
129
Request and response interception, network monitoring, and request routing capabilities for testing and automation.
130
131
```typescript { .api }
132
interface Request {
133
url(): string;
134
method(): string;
135
headers(): { [key: string]: string; };
136
postData(): string | null;
137
response(): Promise<Response | null>;
138
frame(): Frame;
139
}
140
141
interface Response {
142
url(): string;
143
status(): number;
144
headers(): { [key: string]: string; };
145
json(): Promise<any>;
146
text(): Promise<string>;
147
body(): Promise<Buffer>;
148
}
149
150
interface Route {
151
fulfill(response: RouteFullfillResponse): Promise<void>;
152
continue(overrides?: RouteContinueOverrides): Promise<void>;
153
abort(errorCode?: string): Promise<void>;
154
}
155
```
156
157
[Network Control](./network-control.md)
158
159
### Input Simulation
160
161
Comprehensive input simulation including keyboard, mouse, and touch interactions for realistic user behavior testing.
162
163
```typescript { .api }
164
interface Keyboard {
165
down(key: string, options?: KeyboardDownOptions): Promise<void>;
166
up(key: string): Promise<void>;
167
press(key: string, options?: KeyboardPressOptions): Promise<void>;
168
type(text: string, options?: KeyboardTypeOptions): Promise<void>;
169
}
170
171
interface Mouse {
172
move(x: number, y: number, options?: MouseMoveOptions): Promise<void>;
173
click(x: number, y: number, options?: MouseClickOptions): Promise<void>;
174
down(options?: MouseDownOptions): Promise<void>;
175
up(options?: MouseUpOptions): Promise<void>;
176
}
177
```
178
179
[Input Simulation](./input-simulation.md)
180
181
### API Testing
182
183
HTTP API testing capabilities with request/response handling, authentication, and context management.
184
185
```typescript { .api }
186
interface APIRequest {
187
newContext(options?: APIRequestNewContextOptions): Promise<APIRequestContext>;
188
get(url: string, options?: APIRequestGetOptions): Promise<APIResponse>;
189
post(url: string, options?: APIRequestPostOptions): Promise<APIResponse>;
190
put(url: string, options?: APIRequestPutOptions): Promise<APIResponse>;
191
delete(url: string, options?: APIRequestDeleteOptions): Promise<APIResponse>;
192
}
193
194
interface APIResponse {
195
url(): string;
196
status(): number;
197
headers(): { [key: string]: string; };
198
json(): Promise<any>;
199
text(): Promise<string>;
200
ok(): boolean;
201
}
202
```
203
204
[API Testing](./api-testing.md)
205
206
## Global Exports
207
208
### Browser Types
209
210
```typescript { .api }
211
/** Chromium browser type - primary interface for Chromium automation */
212
const chromium: BrowserType;
213
214
/** Firefox browser type - available but not the primary focus */
215
const firefox: BrowserType;
216
217
/** WebKit browser type - available but not the primary focus */
218
const webkit: BrowserType;
219
```
220
221
### Utility Objects
222
223
```typescript { .api }
224
/** HTTP API testing capabilities */
225
const request: APIRequest;
226
227
/** Custom selector engine management */
228
const selectors: Selectors;
229
230
/** Collection of predefined device configurations */
231
const devices: { [deviceName: string]: DeviceDescriptor; };
232
233
/** Error classes for exception handling */
234
const errors: { TimeoutError: typeof TimeoutError; };
235
```
236
237
### Experimental Features
238
239
**⚠️ Warning: Experimental features are subject to change and may be unstable**
240
241
```typescript { .api }
242
/** Electron application automation (experimental) */
243
const _electron: Electron;
244
245
/** Android device automation (experimental) */
246
const _android: Android;
247
248
/** Experimental BiDi Chromium support */
249
const _bidiChromium: BrowserType;
250
251
/** Experimental BiDi Firefox support */
252
const _bidiFirefox: BrowserType;
253
```
254
255
## Core Types
256
257
```typescript { .api }
258
interface LaunchOptions {
259
headless?: boolean | 'new';
260
slowMo?: number;
261
timeout?: number;
262
channel?: string;
263
executablePath?: string;
264
args?: string[];
265
proxy?: { server: string; bypass?: string; username?: string; password?: string; };
266
downloadsPath?: string;
267
chromiumSandbox?: boolean;
268
handleSIGINT?: boolean;
269
handleSIGTERM?: boolean;
270
handleSIGHUP?: boolean;
271
logger?: Logger;
272
env?: { [key: string]: string | number | boolean; };
273
}
274
275
interface BrowserContextOptions {
276
/** Whether to automatically download all the attachments. Defaults to `true`. */
277
acceptDownloads?: boolean;
278
/** Base URL for relative navigation. */
279
baseURL?: string;
280
/** Toggles bypassing page's Content-Security-Policy. Defaults to `false`. */
281
bypassCSP?: boolean;
282
/** Emulates `prefers-colors-scheme` media feature. Defaults to `'light'`. */
283
colorScheme?: null | 'light' | 'dark' | 'no-preference';
284
/** Specify device scale factor (can be thought of as dpr). Defaults to `1`. */
285
deviceScaleFactor?: number;
286
/** An object containing additional HTTP headers to be sent with every request. */
287
extraHTTPHeaders?: { [key: string]: string; };
288
/** Emulates `'forced-colors'` media feature. Defaults to `'none'`. */
289
forcedColors?: null | 'active' | 'none';
290
/** Geolocation data. */
291
geolocation?: { latitude: number; longitude: number; accuracy?: number; };
292
/** Specifies if viewport supports touch events. Defaults to false. */
293
hasTouch?: boolean;
294
/** Credentials for HTTP authentication. */
295
httpCredentials?: { username: string; password: string; };
296
/** Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. */
297
ignoreHTTPSErrors?: boolean;
298
/** Whether the `meta viewport` tag is taken into account. Defaults to `false`. */
299
isMobile?: boolean;
300
/** Whether or not to enable JavaScript in the context. Defaults to `true`. */
301
javaScriptEnabled?: boolean;
302
/** Specify user locale, for example `en-GB`, `de-DE`, etc. */
303
locale?: string;
304
/** Logger sink for Playwright logging. */
305
logger?: Logger;
306
/** Whether to emulate network being offline. Defaults to `false`. */
307
offline?: boolean;
308
/** A list of permissions to grant to all pages in this context. */
309
permissions?: string[];
310
/** Network proxy settings to use with this context. */
311
proxy?: { server: string; bypass?: string; username?: string; password?: string; };
312
/** Enables HAR recording for all pages into the specified path. */
313
recordHar?: RecordHarOptions;
314
/** Enables video recording for all pages into the specified directory. */
315
recordVideo?: RecordVideoOptions;
316
/** Emulates `'prefers-reduced-motion'` media feature. Defaults to `'no-preference'`. */
317
reducedMotion?: null | 'reduce' | 'no-preference';
318
/** Emulates consistent window screen size available inside web page via `window.screen`. */
319
screen?: { width: number; height: number; };
320
/** Changes the timezone of the context. */
321
timezoneId?: string;
322
/** Specific user agent to use in this context. */
323
userAgent?: string;
324
/** Emulates consistent viewport for each page. */
325
viewport?: null | { width: number; height: number; };
326
}
327
328
interface RecordHarOptions {
329
/** Whether to omit content. */
330
omitContent?: boolean;
331
/** Content mode: 'omit', 'embed', or 'attach'. */
332
content?: 'omit' | 'embed' | 'attach';
333
/** Path to save the HAR file. */
334
path: string;
335
/** Recording mode: 'full' or 'minimal'. */
336
mode?: 'full' | 'minimal';
337
/** URL filter pattern. */
338
urlFilter?: string | RegExp;
339
}
340
341
interface RecordVideoOptions {
342
/** Directory to save video files. */
343
dir: string;
344
/** Video frame size. */
345
size?: { width: number; height: number; };
346
}
347
348
interface ConnectOptions {
349
/** Additional headers to send to the browser. */
350
headers?: { [key: string]: string; };
351
/** Slows down Playwright operations by the specified amount of milliseconds. */
352
slowMo?: number;
353
/** Logger sink for Playwright logging. */
354
logger?: Logger;
355
/** Maximum time in milliseconds to wait for the connection to be established. */
356
timeout?: number;
357
}
358
359
interface ConnectOverCDPOptions {
360
/** Browser websocket endpoint to connect to. */
361
wsEndpoint?: string;
362
/** Additional headers to send to the browser. */
363
headers?: { [key: string]: string; };
364
/** Slows down Playwright operations by the specified amount of milliseconds. */
365
slowMo?: number;
366
/** Logger sink for Playwright logging. */
367
logger?: Logger;
368
/** Maximum time in milliseconds to wait for the connection to be established. */
369
timeout?: number;
370
}
371
372
interface Logger {
373
/** Determines whether sink is interested in the logger with the given name and severity. */
374
isEnabled(name: string, severity: 'verbose' | 'info' | 'warning' | 'error'): boolean;
375
/** Log a message. */
376
log(name: string, severity: 'verbose' | 'info' | 'warning' | 'error', message: string | Error, args: ReadonlyArray<Object>, hints: { color?: string; }): void;
377
}
378
379
interface DeviceDescriptor {
380
/** User agent string. */
381
userAgent: string;
382
/** Viewport dimensions. */
383
viewport: { width: number; height: number; };
384
/** Device scale factor. */
385
deviceScaleFactor: number;
386
/** Whether device supports touch. */
387
isMobile: boolean;
388
/** Whether device has touch support. */
389
hasTouch: boolean;
390
/** Default browser to run on this device. */
391
defaultBrowserType?: 'chromium' | 'firefox' | 'webkit';
392
}
393
394
interface PageGotoOptions {
395
/** Referer header value. */
396
referer?: string;
397
/** Maximum operation time in milliseconds. Defaults to `0` - no timeout. */
398
timeout?: number;
399
/** When to consider operation succeeded, defaults to `load`. */
400
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit';
401
}
402
403
interface PageScreenshotOptions {
404
/** An image format. Defaults to 'png'. */
405
type?: 'png' | 'jpeg';
406
/** The file path to save the image to. */
407
path?: string;
408
/** The quality of the image, between 0-100. Not applicable to png images. */
409
quality?: number;
410
/** When true, takes a screenshot of the full scrollable page. Defaults to `false`. */
411
fullPage?: boolean;
412
/** An object which specifies clipping region of the page. */
413
clip?: { x: number; y: number; width: number; height: number; };
414
/** Hides default white background and allows capturing screenshots with transparency. */
415
omitBackground?: boolean;
416
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
417
timeout?: number;
418
/** Caret color in CSS format. */
419
caret?: 'hide' | 'initial';
420
/** When set to `disabled`, screenshot will have scale set to 1. */
421
scale?: 'css' | 'device';
422
}
423
424
interface PageClickOptions {
425
/** Defaults to `left`. */
426
button?: 'left' | 'right' | 'middle';
427
/** defaults to 1. See [UIEvent.detail]. */
428
clickCount?: number;
429
/** Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0. */
430
delay?: number;
431
/** Whether to bypass the actionability checks. Defaults to `false`. */
432
force?: boolean;
433
/** Modifier keys to press. */
434
modifiers?: Array<'Alt' | 'Control' | 'ControlOrMeta' | 'Meta' | 'Shift'>;
435
/** Actions that initiate navigations are waiting for these navigations to happen. */
436
noWaitAfter?: boolean;
437
/** A point to use relative to the top-left corner of element padding box. */
438
position?: { x: number; y: number; };
439
/** When true, the call requires selector to resolve to a single element. */
440
strict?: boolean;
441
/** Maximum time in milliseconds. */
442
timeout?: number;
443
}
444
445
interface PageFillOptions {
446
/** Whether to bypass the actionability checks. Defaults to `false`. */
447
force?: boolean;
448
/** This option has no effect. */
449
noWaitAfter?: boolean;
450
/** When true, the call requires selector to resolve to a single element. */
451
strict?: boolean;
452
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
453
timeout?: number;
454
}
455
456
interface PageTypeOptions {
457
/** Time to wait between key presses in milliseconds. Defaults to 0. */
458
delay?: number;
459
/** Actions that initiate navigations are waiting for these navigations to happen. */
460
noWaitAfter?: boolean;
461
/** When true, the call requires selector to resolve to a single element. */
462
strict?: boolean;
463
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
464
timeout?: number;
465
}
466
467
interface PageWaitForSelectorOptions {
468
/** Defaults to `'visible'`. */
469
state?: 'attached' | 'detached' | 'visible' | 'hidden';
470
/** When true, the call requires selector to resolve to a single element. */
471
strict?: boolean;
472
/** Maximum time in milliseconds. Defaults to `0` - no timeout. */
473
timeout?: number;
474
}
475
476
interface PageFunction<Arg, R> {
477
/** Function to be evaluated in the page context. */
478
(arg: Arg): R | Promise<R>;
479
}
480
481
interface RouteFullfillResponse {
482
/** Response status code, defaults to `200`. */
483
status?: number;
484
/** Response headers. */
485
headers?: { [key: string]: string; };
486
/** Response body. */
487
body?: string | Buffer;
488
/** If set, equals to setting `Content-Type` response header. */
489
contentType?: string;
490
/** Response path for file-based response. */
491
path?: string;
492
}
493
494
interface RouteContinueOverrides {
495
/** HTTP headers to append to the original request. */
496
headers?: { [key: string]: string; };
497
/** HTTP method for the request. */
498
method?: string;
499
/** Post data for the request. */
500
postData?: string | Buffer;
501
/** Request URL. */
502
url?: string;
503
}
504
505
interface CDPSession {
506
/** Send a CDP command. */
507
send<T extends keyof Protocol.CommandParameters>(
508
method: T,
509
params?: Protocol.CommandParameters[T]
510
): Promise<Protocol.CommandReturnValues[T]>;
511
/** Detaches the CDPSession from the target. */
512
detach(): Promise<void>;
513
}
514
515
interface Frame {
516
/** Returns the return value of pageFunction. */
517
evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>;
518
evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>;
519
/** Returns the return value of pageFunction invocation as a JSHandle. */
520
evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
521
evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>;
522
/** Returns the URL of the frame. */
523
url(): string;
524
/** Returns the page containing this frame. */
525
page(): Page;
526
/** Returns the parent frame, if any. Detached frames and main frames return null. */
527
parentFrame(): Frame | null;
528
/** Returns the array of child frames. */
529
childFrames(): Frame[];
530
}
531
532
interface Worker {
533
/** Returns the return value of pageFunction. */
534
evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>;
535
evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>;
536
/** Returns the return value of pageFunction invocation as a JSHandle. */
537
evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
538
evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>;
539
/** Returns the URL of the worker. */
540
url(): string;
541
}
542
543
interface Selectors {
544
/** Register a custom selector engine. */
545
register(name: string, script: string): Promise<void>;
546
/** Set the default selector engine. */
547
setTestIdAttribute(attributeName: string): void;
548
}
549
550
interface SmartHandle<T> {
551
/** JSHandle for any object, ElementHandle for DOM nodes. */
552
}
553
554
interface JSHandle<T = any> {
555
/** Returns the return value of pageFunction. */
556
evaluate<R, Arg>(pageFunction: PageFunctionOn<T, Arg, R>, arg: Arg): Promise<R>;
557
evaluate<R>(pageFunction: PageFunctionOn<T, void, R>, arg?: any): Promise<R>;
558
/** Returns the return value of pageFunction invocation as a JSHandle. */
559
evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<T, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
560
evaluateHandle<R>(pageFunction: PageFunctionOn<T, void, R>, arg?: any): Promise<SmartHandle<R>>;
561
/** The JSHandle.dispose method stops referencing the element handle. */
562
dispose(): Promise<void>;
563
}
564
565
interface Page {
566
/** The page's main frame. */
567
mainFrame(): Frame;
568
/** An array of all frames attached to the page. */
569
frames(): Frame[];
570
/** All of the dedicated WebWorkers associated with the page. */
571
workers(): Worker[];
572
}
573
574
interface ElementHandle<T=Node> extends JSHandle<T> {
575
/** The ElementHandle.ownerFrame method returns the frame containing the element. */
576
ownerFrame(): Promise<Frame | null>;
577
}
578
579
type PageFunctionOn<On, Arg2, R> = string | ((on: On, arg2: Arg2) => R | Promise<R>);
580
```