0
# Browser Control
1
2
Browser-level automation including navigation, window management, JavaScript execution, cookie handling, file operations, and session management.
3
4
## Capabilities
5
6
### Navigation
7
8
Methods for navigating and controlling browser page loading.
9
10
```typescript { .api }
11
/**
12
* Navigate to a URL
13
* @param path - URL or path to navigate to
14
* @param options - Navigation options
15
* @returns Promise resolving to request information or void
16
*/
17
url(path: string, options?: UrlCommandOptions): Promise<WebdriverIO.Request | void>;
18
19
/**
20
* Open a new window or tab
21
* @param url - URL to open in the new window
22
* @param options - Window options
23
* @returns Promise that resolves when window is opened
24
*/
25
newWindow(url: string, options?: object): Promise<void>;
26
27
/**
28
* Switch focus to a different window or tab
29
* @param urlOrTitleToMatch - URL or title to match for window switching
30
* @returns Promise that resolves when window switch is complete
31
*/
32
switchWindow(urlOrTitleToMatch: string): Promise<void>;
33
34
/**
35
* Switch to a specific frame or iframe
36
* @param id - Frame ID, name, index, or element reference
37
* @returns Promise that resolves when frame switch is complete
38
*/
39
switchFrame(id: string | number | null | WebdriverIO.Element): Promise<void>;
40
41
interface UrlCommandOptions {
42
wait?: 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';
43
timeout?: number;
44
referer?: string;
45
}
46
```
47
48
**Usage Examples:**
49
50
```typescript
51
// Basic navigation
52
await browser.url('https://example.com');
53
54
// Navigate with wait options
55
await browser.url('https://example.com/slow-page', {
56
wait: 'networkidle0',
57
timeout: 30000
58
});
59
60
// Open new window
61
await browser.newWindow('https://example.com/popup');
62
63
// Switch windows by title
64
await browser.switchWindow('My App - Dashboard');
65
66
// Switch to iframe
67
const iframe = await browser.$('#my-iframe');
68
await browser.switchFrame(iframe);
69
await browser.switchFrame(null); // Switch back to main frame
70
```
71
72
### JavaScript Execution
73
74
Execute JavaScript code in the browser context.
75
76
```typescript { .api }
77
/**
78
* Execute JavaScript code synchronously in the browser
79
* @param script - JavaScript code string or function to execute
80
* @param args - Arguments to pass to the script
81
* @returns Promise resolving to the script's return value
82
*/
83
execute(script: string | Function, ...args: any[]): Promise<any>;
84
85
/**
86
* Execute JavaScript code asynchronously in the browser
87
* @param script - Async JavaScript code string or function to execute
88
* @param args - Arguments to pass to the script
89
* @returns Promise resolving to the script's return value
90
*/
91
executeAsync(script: string | Function, ...args: any[]): Promise<any>;
92
```
93
94
**Usage Examples:**
95
96
```typescript
97
// Execute simple JavaScript
98
const title = await browser.execute(() => {
99
return document.title;
100
});
101
102
// Execute with arguments
103
const result = await browser.execute((a, b) => {
104
return a + b;
105
}, 5, 3);
106
107
// Execute async JavaScript
108
const asyncResult = await browser.executeAsync((done) => {
109
setTimeout(() => {
110
done(window.location.href);
111
}, 1000);
112
});
113
114
// Execute complex DOM manipulation
115
await browser.execute(() => {
116
const element = document.getElementById('my-element');
117
element.style.backgroundColor = 'red';
118
element.scrollIntoView();
119
});
120
```
121
122
### Window and Viewport Management
123
124
Control browser window size, position, and viewport settings.
125
126
```typescript { .api }
127
/**
128
* Get the current window size
129
* @returns Promise resolving to window dimensions
130
*/
131
getWindowSize(): Promise<{width: number, height: number}>;
132
133
/**
134
* Set the browser window size
135
* @param width - Window width in pixels
136
* @param height - Window height in pixels
137
* @returns Promise that resolves when window is resized
138
*/
139
setWindowSize(width: number, height: number): Promise<void>;
140
141
/**
142
* Set the viewport size for content rendering
143
* @param size - Viewport dimensions object
144
* @returns Promise that resolves when viewport is set
145
*/
146
setViewport(size: object): Promise<void>;
147
```
148
149
**Usage Examples:**
150
151
```typescript
152
// Get current window size
153
const currentSize = await browser.getWindowSize();
154
console.log(`Current size: ${currentSize.width}x${currentSize.height}`);
155
156
// Set window size
157
await browser.setWindowSize(1920, 1080);
158
159
// Set viewport for responsive testing
160
await browser.setViewport({
161
width: 375,
162
height: 667,
163
deviceScaleFactor: 2
164
});
165
```
166
167
### Cookie Management
168
169
Manage browser cookies for session handling and testing.
170
171
```typescript { .api }
172
/**
173
* Get browser cookies
174
* @param names - Optional array of cookie names to retrieve
175
* @returns Promise resolving to array of cookie objects
176
*/
177
getCookies(names?: string[]): Promise<WebDriver.Cookie[]>;
178
179
/**
180
* Set browser cookies
181
* @param cookies - Array of cookie objects to set
182
* @returns Promise that resolves when cookies are set
183
*/
184
setCookies(cookies: WebDriver.Cookie[]): Promise<void>;
185
186
/**
187
* Delete browser cookies
188
* @param names - Optional array of cookie names to delete
189
* @returns Promise that resolves when cookies are deleted
190
*/
191
deleteCookies(names?: string[]): Promise<void>;
192
193
interface WebDriver.Cookie {
194
name: string;
195
value: string;
196
domain?: string;
197
path?: string;
198
expires?: Date;
199
httpOnly?: boolean;
200
secure?: boolean;
201
sameSite?: 'Strict' | 'Lax' | 'None';
202
}
203
```
204
205
**Usage Examples:**
206
207
```typescript
208
// Get all cookies
209
const allCookies = await browser.getCookies();
210
211
// Get specific cookies
212
const authCookies = await browser.getCookies(['session_id', 'auth_token']);
213
214
// Set cookies
215
await browser.setCookies([
216
{
217
name: 'test_cookie',
218
value: 'test_value',
219
domain: '.example.com',
220
path: '/',
221
httpOnly: true,
222
secure: true
223
}
224
]);
225
226
// Delete specific cookies
227
await browser.deleteCookies(['session_id']);
228
229
// Delete all cookies
230
await browser.deleteCookies();
231
```
232
233
### File Operations
234
235
Handle file uploads, downloads, and screenshot capture.
236
237
```typescript { .api }
238
/**
239
* Save a screenshot of the current page
240
* @param filename - Path where screenshot should be saved
241
* @returns Promise that resolves when screenshot is saved
242
*/
243
saveScreenshot(filename: string): Promise<void>;
244
245
/**
246
* Save the current page as a PDF
247
* @param filename - Path where PDF should be saved
248
* @param options - PDF generation options
249
* @returns Promise that resolves when PDF is saved
250
*/
251
savePDF(filename: string, options?: object): Promise<void>;
252
253
/**
254
* Download a file from a URL
255
* @param url - URL of the file to download
256
* @param filename - Local path where file should be saved
257
* @returns Promise that resolves when download is complete
258
*/
259
downloadFile(url: string, filename: string): Promise<void>;
260
261
/**
262
* Upload a file and return the remote file path
263
* @param localPath - Local path to the file to upload
264
* @returns Promise resolving to the remote file path
265
*/
266
uploadFile(localPath: string): Promise<string>;
267
268
/**
269
* Save a screen recording
270
* @param filename - Path where recording should be saved
271
* @returns Promise that resolves when recording is saved
272
*/
273
saveRecordingScreen(filename: string): Promise<void>;
274
```
275
276
**Usage Examples:**
277
278
```typescript
279
// Take screenshot
280
await browser.saveScreenshot('./screenshots/homepage.png');
281
282
// Save as PDF with options
283
await browser.savePDF('./reports/page.pdf', {
284
format: 'A4',
285
margin: { top: 20, bottom: 20, left: 20, right: 20 }
286
});
287
288
// Upload file for form submission
289
const remotePath = await browser.uploadFile('./test-files/document.pdf');
290
const fileInput = await browser.$('input[type="file"]');
291
await fileInput.setValue(remotePath);
292
293
// Download file
294
await browser.downloadFile('https://example.com/report.pdf', './downloads/report.pdf');
295
```
296
297
### Input and Interaction
298
299
Browser-level input methods and interaction utilities.
300
301
```typescript { .api }
302
/**
303
* Send keyboard input to the browser
304
* @param value - String or array of keys to send
305
* @returns Promise that resolves when keys are sent
306
*/
307
keys(value: string | string[]): Promise<void>;
308
309
/**
310
* Scroll the page to specific coordinates
311
* @param x - Horizontal scroll position
312
* @param y - Vertical scroll position
313
* @returns Promise that resolves when scrolling is complete
314
*/
315
scroll(x: number, y: number): Promise<void>;
316
317
/**
318
* Create an action sequence for complex interactions
319
* @param type - Action type (e.g., 'pointer', 'key')
320
* @param options - Action configuration options
321
* @returns Action object for chaining
322
*/
323
action(type: string, options?: object): WebdriverIO.Action;
324
325
/**
326
* Perform multiple action sequences
327
* @param actions - Array of action sequence configurations
328
* @returns Promise that resolves when actions are complete
329
*/
330
actions(actions: object[]): Promise<void>;
331
332
const Key: {
333
Ctrl: string;
334
Enter: string;
335
Tab: string;
336
Escape: string;
337
Space: string;
338
Delete: string;
339
Backspace: string;
340
ArrowUp: string;
341
ArrowDown: string;
342
ArrowLeft: string;
343
ArrowRight: string;
344
F1: string;
345
F2: string;
346
F3: string;
347
F4: string;
348
F5: string;
349
F6: string;
350
F7: string;
351
F8: string;
352
F9: string;
353
F10: string;
354
F11: string;
355
F12: string;
356
};
357
```
358
359
**Usage Examples:**
360
361
```typescript
362
import { Key } from 'webdriverio';
363
364
// Send keyboard shortcuts
365
await browser.keys([Key.Ctrl, 'a']); // Select all
366
await browser.keys([Key.Ctrl, 'c']); // Copy
367
await browser.keys([Key.Ctrl, 'v']); // Paste
368
369
// Send text input
370
await browser.keys('Hello World');
371
372
// Scroll page
373
await browser.scroll(0, 500); // Scroll down 500px
374
375
// Complex action sequences
376
const actions = await browser.action('pointer');
377
await actions
378
.move({ x: 100, y: 100 })
379
.down()
380
.move({ x: 200, y: 200 })
381
.up()
382
.perform();
383
```
384
385
### Session Control
386
387
Methods for controlling the browser session lifecycle and state.
388
389
```typescript { .api }
390
/**
391
* Pause execution for a specified duration
392
* @param milliseconds - Duration to pause in milliseconds
393
* @returns Promise that resolves after the pause
394
*/
395
pause(milliseconds: number): Promise<void>;
396
397
/**
398
* Start an interactive debugging session
399
* @returns Promise that resolves when debugging session ends
400
*/
401
debug(): Promise<void>;
402
403
/**
404
* Reload the current WebDriver session
405
* @returns Promise that resolves when session is reloaded
406
*/
407
reloadSession(): Promise<void>;
408
409
/**
410
* Set various timeout values for the session
411
* @param timeouts - Timeout configuration object
412
* @returns Promise that resolves when timeouts are set
413
*/
414
setTimeout(timeouts: object): Promise<void>;
415
416
/**
417
* Wait until a condition is met
418
* @param condition - Function that returns true when condition is met
419
* @param options - Wait options including timeout and interval
420
* @returns Promise resolving to the condition function's return value
421
*/
422
waitUntil(condition: Function, options?: object): Promise<any>;
423
```
424
425
**Usage Examples:**
426
427
```typescript
428
// Pause execution
429
await browser.pause(3000); // Wait 3 seconds
430
431
// Start debugging (opens REPL)
432
await browser.debug();
433
434
// Set timeouts
435
await browser.setTimeout({
436
'implicit': 5000,
437
'page load': 30000,
438
'script': 10000
439
});
440
441
// Wait for custom condition
442
await browser.waitUntil(async () => {
443
const element = await browser.$('#dynamic-content');
444
return await element.isDisplayed();
445
}, {
446
timeout: 10000,
447
timeoutMsg: 'Dynamic content did not appear'
448
});
449
450
// Wait for page title change
451
await browser.waitUntil(async () => {
452
const title = await browser.getTitle();
453
return title.includes('Dashboard');
454
});
455
```
456
457
### Browser Performance & Emulation
458
459
Methods for controlling browser performance characteristics and emulating different environments.
460
461
```typescript { .api }
462
/**
463
* Emulate device characteristics and browser features
464
* @param options - Emulation configuration object
465
* @returns Promise that resolves when emulation is set
466
*/
467
emulate(options: {
468
userAgent?: string;
469
viewport?: { width: number; height: number };
470
deviceScaleFactor?: number;
471
isMobile?: boolean;
472
hasTouch?: boolean;
473
isLandscape?: boolean;
474
geolocation?: { latitude: number; longitude: number; accuracy?: number };
475
timezone?: string;
476
locale?: string;
477
permissions?: string[];
478
colorScheme?: 'light' | 'dark' | 'no-preference';
479
reducedMotion?: 'reduce' | 'no-preference';
480
forcedColors?: 'active' | 'none';
481
}): Promise<void>;
482
483
/**
484
* Throttle CPU performance
485
* @param rate - CPU throttling rate (1 = no throttling, 4 = 4x slower)
486
* @returns Promise that resolves when CPU throttling is applied
487
*/
488
throttleCPU(rate: number): Promise<void>;
489
490
/**
491
* Throttle network performance
492
* @param conditions - Network throttling conditions
493
* @returns Promise that resolves when network throttling is applied
494
*/
495
throttleNetwork(conditions: {
496
offline?: boolean;
497
downloadThroughput?: number;
498
uploadThroughput?: number;
499
latency?: number;
500
}): Promise<void>;
501
502
/**
503
* General throttling method for various browser resources
504
* @param type - Type of throttling to apply
505
* @param conditions - Throttling conditions
506
* @returns Promise that resolves when throttling is applied
507
*/
508
throttle(type: 'cpu' | 'network', conditions: object): Promise<void>;
509
```
510
511
**Usage Examples:**
512
513
```typescript
514
// Emulate mobile device
515
await browser.emulate({
516
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',
517
viewport: { width: 375, height: 667 },
518
deviceScaleFactor: 2,
519
isMobile: true,
520
hasTouch: true
521
});
522
523
// Emulate geolocation
524
await browser.emulate({
525
geolocation: { latitude: 37.7749, longitude: -122.4194 }
526
});
527
528
// Emulate dark mode
529
await browser.emulate({
530
colorScheme: 'dark'
531
});
532
533
// Throttle CPU for performance testing
534
await browser.throttleCPU(4); // 4x slower
535
536
// Throttle network to simulate slow connection
537
await browser.throttleNetwork({
538
downloadThroughput: 1.5 * 1024 * 1024 / 8, // 1.5Mbps
539
uploadThroughput: 750 * 1024 / 8, // 750Kbps
540
latency: 40 // 40ms
541
});
542
543
// Simulate offline mode
544
await browser.throttleNetwork({ offline: true });
545
```
546
547
### Session Management
548
549
Methods for managing the browser session lifecycle and reloading sessions.
550
551
```typescript { .api }
552
/**
553
* Reload the current WebDriver session with the same capabilities
554
* @returns Promise that resolves when session is reloaded
555
*/
556
reloadSession(): Promise<void>;
557
558
/**
559
* Add an initialization script that runs before page loads
560
* @param script - JavaScript code or function to run on page load
561
* @returns Promise resolving to script handle for removal
562
*/
563
addInitScript(script: string | Function): Promise<{ remove(): Promise<void> }>;
564
```
565
566
**Usage Examples:**
567
568
```typescript
569
// Reload session to reset browser state
570
await browser.reloadSession();
571
572
// Add script to run before each page load
573
const scriptHandle = await browser.addInitScript(() => {
574
// Mock geolocation API
575
Object.defineProperty(navigator, 'geolocation', {
576
value: {
577
getCurrentPosition: (success) => {
578
success({ coords: { latitude: 37.7749, longitude: -122.4194 } });
579
}
580
}
581
});
582
});
583
584
// Navigate to pages - script runs automatically
585
await browser.url('https://example.com');
586
587
// Remove the script when no longer needed
588
await scriptHandle.remove();
589
```
590
591
### Advanced File Operations
592
593
Additional file operations for screen recording and advanced browser integration.
594
595
```typescript { .api }
596
/**
597
* Save a screen recording of browser activity
598
* @param filename - Path where recording should be saved
599
* @param options - Recording options
600
* @returns Promise that resolves when recording is saved
601
*/
602
saveRecordingScreen(filename: string, options?: {
603
duration?: number;
604
fps?: number;
605
}): Promise<void>;
606
607
/**
608
* Get access to Puppeteer instance (Chrome/Edge only)
609
* @returns Promise resolving to Puppeteer browser or page instance
610
*/
611
getPuppeteer(): Promise<any>;
612
```
613
614
**Usage Examples:**
615
616
```typescript
617
// Start screen recording, perform actions, then save
618
await browser.url('https://example.com');
619
// ... perform test actions ...
620
await browser.saveRecordingScreen('./test-recording.mp4', {
621
duration: 30000, // 30 seconds
622
fps: 30
623
});
624
625
// Access Puppeteer for advanced Chrome features (Chrome/Edge only)
626
if (browser.capabilities.browserName === 'chrome') {
627
const puppeteer = await browser.getPuppeteer();
628
// Use Puppeteer-specific APIs
629
await puppeteer.setUserAgent('Custom User Agent');
630
}
631
```
632
633
### Custom Commands
634
635
Extend browser functionality with custom commands.
636
637
```typescript { .api }
638
/**
639
* Add a custom command to the browser instance
640
* @param name - Name of the custom command
641
* @param func - Function implementation of the command
642
* @param attachToElement - Whether to also attach to element instances
643
* @returns Void
644
*/
645
addCommand(name: string, func: Function, attachToElement?: boolean): void;
646
647
/**
648
* Overwrite an existing command with custom implementation
649
* @param name - Name of the command to overwrite
650
* @param func - New function implementation
651
* @param attachToElement - Whether to also attach to element instances
652
* @returns Void
653
*/
654
overwriteCommand(name: string, func: Function, attachToElement?: boolean): void;
655
656
/**
657
* Call a function with the browser instance as context
658
* @param callback - Function to call with browser as context
659
* @returns Promise resolving to the callback's return value
660
*/
661
call(callback: Function): Promise<any>;
662
```
663
664
**Usage Examples:**
665
666
```typescript
667
// Add custom command
668
browser.addCommand('loginAs', async function (username: string, password: string) {
669
await this.$('#username').setValue(username);
670
await this.$('#password').setValue(password);
671
await this.$('#login-btn').click();
672
});
673
674
// Use custom command
675
await browser.loginAs('testuser', 'password123');
676
677
// Overwrite existing command
678
browser.overwriteCommand('click', async function (originalClick, options) {
679
console.log('Clicking element:', this.selector);
680
return await originalClick.call(this, options);
681
}, true);
682
683
// Call function with browser context
684
const result = await browser.call(async function() {
685
const title = await this.getTitle();
686
const url = await this.getUrl();
687
return { title, url };
688
});
689
```