CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webdriverio

Next-gen browser and mobile automation test framework for Node.js

Pending
Overview
Eval results
Files

browser-control.mddocs/

Browser Control

Browser-level automation including navigation, window management, JavaScript execution, cookie handling, file operations, and session management.

Capabilities

Navigation

Methods for navigating and controlling browser page loading.

/**
 * Navigate to a URL
 * @param path - URL or path to navigate to
 * @param options - Navigation options
 * @returns Promise resolving to request information or void
 */
url(path: string, options?: UrlCommandOptions): Promise<WebdriverIO.Request | void>;

/**
 * Open a new window or tab
 * @param url - URL to open in the new window
 * @param options - Window options
 * @returns Promise that resolves when window is opened
 */
newWindow(url: string, options?: object): Promise<void>;

/**
 * Switch focus to a different window or tab
 * @param urlOrTitleToMatch - URL or title to match for window switching
 * @returns Promise that resolves when window switch is complete
 */
switchWindow(urlOrTitleToMatch: string): Promise<void>;

/**
 * Switch to a specific frame or iframe
 * @param id - Frame ID, name, index, or element reference
 * @returns Promise that resolves when frame switch is complete
 */
switchFrame(id: string | number | null | WebdriverIO.Element): Promise<void>;

interface UrlCommandOptions {
  wait?: 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';
  timeout?: number;
  referer?: string;
}

Usage Examples:

// Basic navigation
await browser.url('https://example.com');

// Navigate with wait options
await browser.url('https://example.com/slow-page', {
  wait: 'networkidle0',
  timeout: 30000
});

// Open new window
await browser.newWindow('https://example.com/popup');

// Switch windows by title
await browser.switchWindow('My App - Dashboard');

// Switch to iframe
const iframe = await browser.$('#my-iframe');
await browser.switchFrame(iframe);
await browser.switchFrame(null); // Switch back to main frame

JavaScript Execution

Execute JavaScript code in the browser context.

/**
 * Execute JavaScript code synchronously in the browser
 * @param script - JavaScript code string or function to execute
 * @param args - Arguments to pass to the script
 * @returns Promise resolving to the script's return value
 */
execute(script: string | Function, ...args: any[]): Promise<any>;

/**
 * Execute JavaScript code asynchronously in the browser
 * @param script - Async JavaScript code string or function to execute
 * @param args - Arguments to pass to the script
 * @returns Promise resolving to the script's return value
 */
executeAsync(script: string | Function, ...args: any[]): Promise<any>;

Usage Examples:

// Execute simple JavaScript
const title = await browser.execute(() => {
  return document.title;
});

// Execute with arguments
const result = await browser.execute((a, b) => {
  return a + b;
}, 5, 3);

// Execute async JavaScript
const asyncResult = await browser.executeAsync((done) => {
  setTimeout(() => {
    done(window.location.href);
  }, 1000);
});

// Execute complex DOM manipulation
await browser.execute(() => {
  const element = document.getElementById('my-element');
  element.style.backgroundColor = 'red';
  element.scrollIntoView();
});

Window and Viewport Management

Control browser window size, position, and viewport settings.

/**
 * Get the current window size
 * @returns Promise resolving to window dimensions
 */
getWindowSize(): Promise<{width: number, height: number}>;

/**
 * Set the browser window size
 * @param width - Window width in pixels
 * @param height - Window height in pixels
 * @returns Promise that resolves when window is resized
 */
setWindowSize(width: number, height: number): Promise<void>;

/**
 * Set the viewport size for content rendering
 * @param size - Viewport dimensions object
 * @returns Promise that resolves when viewport is set
 */
setViewport(size: object): Promise<void>;

Usage Examples:

// Get current window size
const currentSize = await browser.getWindowSize();
console.log(`Current size: ${currentSize.width}x${currentSize.height}`);

// Set window size
await browser.setWindowSize(1920, 1080);

// Set viewport for responsive testing
await browser.setViewport({
  width: 375,
  height: 667,
  deviceScaleFactor: 2
});

Cookie Management

Manage browser cookies for session handling and testing.

/**
 * Get browser cookies
 * @param names - Optional array of cookie names to retrieve
 * @returns Promise resolving to array of cookie objects
 */
getCookies(names?: string[]): Promise<WebDriver.Cookie[]>;

/**
 * Set browser cookies
 * @param cookies - Array of cookie objects to set
 * @returns Promise that resolves when cookies are set
 */
setCookies(cookies: WebDriver.Cookie[]): Promise<void>;

/**
 * Delete browser cookies
 * @param names - Optional array of cookie names to delete
 * @returns Promise that resolves when cookies are deleted
 */
deleteCookies(names?: string[]): Promise<void>;

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

Usage Examples:

// Get all cookies
const allCookies = await browser.getCookies();

// Get specific cookies
const authCookies = await browser.getCookies(['session_id', 'auth_token']);

// Set cookies
await browser.setCookies([
  {
    name: 'test_cookie',
    value: 'test_value',
    domain: '.example.com',
    path: '/',
    httpOnly: true,
    secure: true
  }
]);

// Delete specific cookies
await browser.deleteCookies(['session_id']);

// Delete all cookies
await browser.deleteCookies();

File Operations

Handle file uploads, downloads, and screenshot capture.

/**
 * Save a screenshot of the current page
 * @param filename - Path where screenshot should be saved
 * @returns Promise that resolves when screenshot is saved
 */
saveScreenshot(filename: string): Promise<void>;

/**
 * Save the current page as a PDF
 * @param filename - Path where PDF should be saved
 * @param options - PDF generation options
 * @returns Promise that resolves when PDF is saved
 */
savePDF(filename: string, options?: object): Promise<void>;

/**
 * Download a file from a URL
 * @param url - URL of the file to download
 * @param filename - Local path where file should be saved
 * @returns Promise that resolves when download is complete
 */
downloadFile(url: string, filename: string): Promise<void>;

/**
 * Upload a file and return the remote file path
 * @param localPath - Local path to the file to upload
 * @returns Promise resolving to the remote file path
 */
uploadFile(localPath: string): Promise<string>;

/**
 * Save a screen recording
 * @param filename - Path where recording should be saved
 * @returns Promise that resolves when recording is saved
 */
saveRecordingScreen(filename: string): Promise<void>;

Usage Examples:

// Take screenshot
await browser.saveScreenshot('./screenshots/homepage.png');

// Save as PDF with options
await browser.savePDF('./reports/page.pdf', {
  format: 'A4',
  margin: { top: 20, bottom: 20, left: 20, right: 20 }
});

// Upload file for form submission
const remotePath = await browser.uploadFile('./test-files/document.pdf');
const fileInput = await browser.$('input[type="file"]');
await fileInput.setValue(remotePath);

// Download file
await browser.downloadFile('https://example.com/report.pdf', './downloads/report.pdf');

Input and Interaction

Browser-level input methods and interaction utilities.

/**
 * Send keyboard input to the browser
 * @param value - String or array of keys to send
 * @returns Promise that resolves when keys are sent
 */
keys(value: string | string[]): Promise<void>;

/**
 * Scroll the page to specific coordinates
 * @param x - Horizontal scroll position
 * @param y - Vertical scroll position
 * @returns Promise that resolves when scrolling is complete
 */
scroll(x: number, y: number): Promise<void>;

/**
 * Create an action sequence for complex interactions
 * @param type - Action type (e.g., 'pointer', 'key')
 * @param options - Action configuration options
 * @returns Action object for chaining
 */
action(type: string, options?: object): WebdriverIO.Action;

/**
 * Perform multiple action sequences
 * @param actions - Array of action sequence configurations
 * @returns Promise that resolves when actions are complete
 */
actions(actions: object[]): Promise<void>;

const Key: {
  Ctrl: string;
  Enter: string;
  Tab: string;
  Escape: string;
  Space: string;
  Delete: string;
  Backspace: string;
  ArrowUp: string;
  ArrowDown: string;
  ArrowLeft: string;
  ArrowRight: string;
  F1: string;
  F2: string;
  F3: string;
  F4: string;
  F5: string;
  F6: string;
  F7: string;
  F8: string;
  F9: string;
  F10: string;
  F11: string;
  F12: string;
};

Usage Examples:

import { Key } from 'webdriverio';

// Send keyboard shortcuts
await browser.keys([Key.Ctrl, 'a']); // Select all
await browser.keys([Key.Ctrl, 'c']); // Copy
await browser.keys([Key.Ctrl, 'v']); // Paste

// Send text input
await browser.keys('Hello World');

// Scroll page
await browser.scroll(0, 500); // Scroll down 500px

// Complex action sequences
const actions = await browser.action('pointer');
await actions
  .move({ x: 100, y: 100 })
  .down()
  .move({ x: 200, y: 200 })
  .up()
  .perform();

Session Control

Methods for controlling the browser session lifecycle and state.

/**
 * Pause execution for a specified duration
 * @param milliseconds - Duration to pause in milliseconds
 * @returns Promise that resolves after the pause
 */
pause(milliseconds: number): Promise<void>;

/**
 * Start an interactive debugging session
 * @returns Promise that resolves when debugging session ends
 */
debug(): Promise<void>;

/**
 * Reload the current WebDriver session
 * @returns Promise that resolves when session is reloaded
 */
reloadSession(): Promise<void>;

/**
 * Set various timeout values for the session
 * @param timeouts - Timeout configuration object
 * @returns Promise that resolves when timeouts are set
 */
setTimeout(timeouts: object): Promise<void>;

/**
 * Wait until a condition is met
 * @param condition - Function that returns true when condition is met
 * @param options - Wait options including timeout and interval
 * @returns Promise resolving to the condition function's return value
 */
waitUntil(condition: Function, options?: object): Promise<any>;

Usage Examples:

// Pause execution
await browser.pause(3000); // Wait 3 seconds

// Start debugging (opens REPL)
await browser.debug();

// Set timeouts
await browser.setTimeout({
  'implicit': 5000,
  'page load': 30000,
  'script': 10000
});

// Wait for custom condition
await browser.waitUntil(async () => {
  const element = await browser.$('#dynamic-content');
  return await element.isDisplayed();
}, {
  timeout: 10000,
  timeoutMsg: 'Dynamic content did not appear'
});

// Wait for page title change
await browser.waitUntil(async () => {
  const title = await browser.getTitle();
  return title.includes('Dashboard');
});

Browser Performance & Emulation

Methods for controlling browser performance characteristics and emulating different environments.

/**
 * Emulate device characteristics and browser features
 * @param options - Emulation configuration object
 * @returns Promise that resolves when emulation is set
 */
emulate(options: {
  userAgent?: string;
  viewport?: { width: number; height: number };
  deviceScaleFactor?: number;
  isMobile?: boolean;
  hasTouch?: boolean;
  isLandscape?: boolean;
  geolocation?: { latitude: number; longitude: number; accuracy?: number };
  timezone?: string;
  locale?: string;
  permissions?: string[];
  colorScheme?: 'light' | 'dark' | 'no-preference';
  reducedMotion?: 'reduce' | 'no-preference';
  forcedColors?: 'active' | 'none';
}): Promise<void>;

/**
 * Throttle CPU performance
 * @param rate - CPU throttling rate (1 = no throttling, 4 = 4x slower)
 * @returns Promise that resolves when CPU throttling is applied
 */
throttleCPU(rate: number): Promise<void>;

/**
 * Throttle network performance
 * @param conditions - Network throttling conditions
 * @returns Promise that resolves when network throttling is applied
 */
throttleNetwork(conditions: {
  offline?: boolean;
  downloadThroughput?: number;
  uploadThroughput?: number;
  latency?: number;
}): Promise<void>;

/**
 * General throttling method for various browser resources
 * @param type - Type of throttling to apply
 * @param conditions - Throttling conditions
 * @returns Promise that resolves when throttling is applied
 */
throttle(type: 'cpu' | 'network', conditions: object): Promise<void>;

Usage Examples:

// Emulate mobile device
await browser.emulate({
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',
  viewport: { width: 375, height: 667 },
  deviceScaleFactor: 2,
  isMobile: true,
  hasTouch: true
});

// Emulate geolocation
await browser.emulate({
  geolocation: { latitude: 37.7749, longitude: -122.4194 }
});

// Emulate dark mode
await browser.emulate({
  colorScheme: 'dark'
});

// Throttle CPU for performance testing
await browser.throttleCPU(4); // 4x slower

// Throttle network to simulate slow connection
await browser.throttleNetwork({
  downloadThroughput: 1.5 * 1024 * 1024 / 8, // 1.5Mbps
  uploadThroughput: 750 * 1024 / 8,           // 750Kbps
  latency: 40                                  // 40ms
});

// Simulate offline mode
await browser.throttleNetwork({ offline: true });

Session Management

Methods for managing the browser session lifecycle and reloading sessions.

/**
 * Reload the current WebDriver session with the same capabilities
 * @returns Promise that resolves when session is reloaded
 */
reloadSession(): Promise<void>;

/**
 * Add an initialization script that runs before page loads
 * @param script - JavaScript code or function to run on page load
 * @returns Promise resolving to script handle for removal
 */
addInitScript(script: string | Function): Promise<{ remove(): Promise<void> }>;

Usage Examples:

// Reload session to reset browser state
await browser.reloadSession();

// Add script to run before each page load
const scriptHandle = await browser.addInitScript(() => {
  // Mock geolocation API
  Object.defineProperty(navigator, 'geolocation', {
    value: {
      getCurrentPosition: (success) => {
        success({ coords: { latitude: 37.7749, longitude: -122.4194 } });
      }
    }
  });
});

// Navigate to pages - script runs automatically
await browser.url('https://example.com');

// Remove the script when no longer needed
await scriptHandle.remove();

Advanced File Operations

Additional file operations for screen recording and advanced browser integration.

/**
 * Save a screen recording of browser activity
 * @param filename - Path where recording should be saved
 * @param options - Recording options
 * @returns Promise that resolves when recording is saved
 */
saveRecordingScreen(filename: string, options?: {
  duration?: number;
  fps?: number;
}): Promise<void>;

/**
 * Get access to Puppeteer instance (Chrome/Edge only)
 * @returns Promise resolving to Puppeteer browser or page instance
 */
getPuppeteer(): Promise<any>;

Usage Examples:

// Start screen recording, perform actions, then save
await browser.url('https://example.com');
// ... perform test actions ...
await browser.saveRecordingScreen('./test-recording.mp4', {
  duration: 30000, // 30 seconds
  fps: 30
});

// Access Puppeteer for advanced Chrome features (Chrome/Edge only)
if (browser.capabilities.browserName === 'chrome') {
  const puppeteer = await browser.getPuppeteer();
  // Use Puppeteer-specific APIs
  await puppeteer.setUserAgent('Custom User Agent');
}

Custom Commands

Extend browser functionality with custom commands.

/**
 * Add a custom command to the browser instance
 * @param name - Name of the custom command
 * @param func - Function implementation of the command
 * @param attachToElement - Whether to also attach to element instances
 * @returns Void
 */
addCommand(name: string, func: Function, attachToElement?: boolean): void;

/**
 * Overwrite an existing command with custom implementation
 * @param name - Name of the command to overwrite
 * @param func - New function implementation
 * @param attachToElement - Whether to also attach to element instances
 * @returns Void
 */
overwriteCommand(name: string, func: Function, attachToElement?: boolean): void;

/**
 * Call a function with the browser instance as context
 * @param callback - Function to call with browser as context
 * @returns Promise resolving to the callback's return value
 */
call(callback: Function): Promise<any>;

Usage Examples:

// Add custom command
browser.addCommand('loginAs', async function (username: string, password: string) {
  await this.$('#username').setValue(username);
  await this.$('#password').setValue(password);
  await this.$('#login-btn').click();
});

// Use custom command
await browser.loginAs('testuser', 'password123');

// Overwrite existing command
browser.overwriteCommand('click', async function (originalClick, options) {
  console.log('Clicking element:', this.selector);
  return await originalClick.call(this, options);
}, true);

// Call function with browser context
const result = await browser.call(async function() {
  const title = await this.getTitle();
  const url = await this.getUrl();
  return { title, url };
});

Install with Tessl CLI

npx tessl i tessl/npm-webdriverio

docs

browser-control.md

dialog-handling.md

element-interaction.md

element-selection.md

index.md

mobile-automation.md

session-management.md

testing-utilities.md

tile.json