### Start Screen Recording Example (Appium Windows Driver) Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Demonstrates how to start screen recording with specific parameters using either `executeScript` or the direct driver method. Ensure FFmpeg is installed. ```javascript // Via executeScript await driver.executeScript('windows: startRecordingScreen', [{ fps: 20, captureCursor: true, timeLimit: 300 }]); // Or via driver method (easier) await driver.windowsStartRecordingScreen({ fps: 20, captureCursor: true, timeLimit: 300 }); ``` -------------------------------- ### Start Screen Recording (Appium Windows Driver) Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Starts recording the screen in the background. Supports various options for video quality, cursor capture, and time limits. Ensure FFmpeg is installed. ```typescript execute_script('windows: startRecordingScreen', [{ videoFilter: 'string?', fps: 'number?', preset: 'string?', captureCursor: 'boolean?', captureClicks: 'boolean?', audioInput: 'string?', timeLimit: 'number?', forceRestart: 'boolean?' }]) ``` -------------------------------- ### Install Dependencies Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Run this command after checking out the repository to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Launch App Example (Appium Windows Driver) Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Provides examples for launching the app using both `executeScript` and the direct driver method. ```javascript await driver.executeScript('windows: launchApp'); // Or use driver method (easier) await driver.windowsLaunchApp(); ``` -------------------------------- ### Start WinAppDriver and Create Session Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Starts the WinAppDriver server and initiates a new session using provided capabilities. This example assumes the server is not already running externally. ```typescript const wad = new WinAppDriver(logger, {port: 4724}); await wad.start({ 'appium:app': 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App' }); // Server now running and session created ``` -------------------------------- ### Built-in Server Startup Steps Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Steps to start the WinAppDriver server using its built-in capabilities. This involves allocating a port, starting the process, and waiting for the server to become available. ```text 1. Allocate port (auto or explicit) 2. Create WADProcess instance 3. Call process.start() 4. Create WADProxy instance 5. Wait for server to respond to /status (10000ms timeout, 1000ms retry interval) 6. Register exit handler on process 7. Track PID for cleanup on process exit ``` -------------------------------- ### Complete Appium Windows Driver Configuration Example Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/configuration.md A comprehensive example demonstrating various capabilities for configuring an Appium Windows Driver session, including app selection, timeouts, server settings, and scripts. ```typescript import {remote} from 'webdriverio'; const opts = { platformName: 'Windows', 'appium:automationName': 'Windows', // App selection 'appium:app': 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App', // OR // 'appium:appTopLevelWindow': '0x12345', // OR // 'appium:app': 'C:\\Windows\\System32\\notepad.exe', // App configuration 'appium:appArguments': 'file.txt', 'appium:appWorkingDir': 'C:\\Users\\user\\app', // Session timeouts 'appium:createSessionTimeout': 30000, // milliseconds 'ms:waitForAppLaunch': 10, // seconds 'appium:newCommandTimeout': 300, // seconds // Server configuration 'appium:systemPort': 5556, 'appium:wadUrl': 'http://127.0.0.1:4724/wd/hub', // Server behavior 'ms:forcequit': true, 'ms:experimental-webdriver': false, // Setup/cleanup scripts 'appium:prerun': { command: 'Get-Process' }, 'appium:postrun': { script: 'Write-Host "Cleanup"' } }; const client = await remote({ hostname: 'localhost', port: 4723, path: '/wd/hub', capabilities: opts }); ``` -------------------------------- ### windows: startRecordingScreen Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Starts recording the display in the background. Requires FFmpeg to be installed. The resulting video is H264 encoded. ```APIDOC ## windows: startRecordingScreen ### Description Record the display in background while the automated test is running. This method requires [FFMPEG](https://www.ffmpeg.org/download.html) to be installed and present in PATH. The resulting video uses H264 codec and is ready to be played by media players built-in into web browsers. ### Method POST ### Endpoint /session/{sessionid}/appium/device/start_recording_screen ### Parameters #### Query Parameters - **videoFilter** (string) - Optional - The video filter spec to apply for ffmpeg. See https://trac.ffmpeg.org/wiki/FilteringGuide for more details on the possible values. Example: `scale=ifnot(gte(iw\,1024)\,iw\,1024):-2` - **fps** (number) - Optional - The count of frames per second in the resulting video. The default value is `15`. Example: `10` - **preset** (string) - Optional - One of the supported encoding presets. Possible values are: `ultrafast`, `superfast`, `veryfast` (the default value), `faster`, `fast`, `medium`, `slow`, `slower`, `veryslow`. Example: `fast` - **captureCursor** (boolean) - Optional - Whether to capture the mouse cursor while recording the screen. `false` by default. Example: `true` - **captureClicks** (boolean) - Optional - Whether to capture mouse clicks while recording the screen. `false` by default. Example: `true` - **timeLimit** (number) - Optional - The maximum recording time, in seconds. The default value is 600 seconds (10 minutes). Example: `300` - **forceRestart** (boolean) - Optional - Whether to ignore the call if a screen recording is currently running (`false`) or to start a new recording immediately and terminate the existing one if running (`true`, the default value). Example: `true` ### Request Example ```json { "script": "windows: startRecordingScreen", "args": [ { "videoFilter": "scale=ifnot(gte(iw\,1024)\,iw\,1024):-2", "fps": 10, "preset": "fast", "captureCursor": true, "captureClicks": true, "timeLimit": 300, "forceRestart": true } ] } ``` ### Response #### Success Response (200) - **value** (string) - Base64-encoded content of the recorded media file. ``` -------------------------------- ### KeyAction Examples Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/types.md Examples demonstrating various KeyAction configurations for typing, pausing, and key state manipulation. ```typescript {pause: 100} // Wait 100ms ``` ```typescript {text: 'Hello'} // Type text ``` ```typescript {virtualKeyCode: 0x09} // TAB key (full press) ``` ```typescript {virtualKeyCode: 0x10, down: true} // Shift down ``` ```typescript {virtualKeyCode: 0x10, down: false} // Shift up ``` -------------------------------- ### Start Screen Recording Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Initiates screen recording to an MP4 file using FFmpeg. Requires FFmpeg to be installed and accessible in the system's PATH. Customize recording parameters like FPS, preset, and cursor capture as needed. ```typescript async windowsStartRecordingScreen(options?: StartRecordingOptions): Promise ``` ```typescript // Start basic recording await driver.windowsStartRecordingScreen(); // Start with custom settings await driver.windowsStartRecordingScreen({ fps: 20, preset: 'fast', captureCursor: true, captureClicks: true, timeLimit: 300, // 5 minutes }); // Limit video width to 1024px await driver.windowsStartRecordingScreen({ videoFilter: 'scale=ifnot(gte(iw\,1024)\,iw\,1024):-2', }); ``` -------------------------------- ### Create Session Example Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Example of creating a new Appium session for Windows. This involves defining capabilities like platformName, automationName, and the application to launch. ```typescript const caps = { platformName: 'Windows', 'appium:automationName': 'Windows', 'appium:app': 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App', }; const [sessionId, capabilities] = await driver.createSession({ alwaysMatch: caps }); ``` -------------------------------- ### install-wad Driver Script Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Instructions on how to use the `install-wad` script to install the WinAppDriver server. ```APIDOC ## install-wad Driver Script This script is used to install the given or latest stable version of WinAppDriver server from the [GitHub releases](https://github.com/microsoft/WinAppDriver/releases) page. ### Usage Run `appium driver run windows install-wad `, where `optional_wad_version` must be either valid WAD version number or should not be present (the latest stable version is used then). ``` -------------------------------- ### Execute Keyboard Input to Type Text Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Example of typing 'Hello World' using `executeScript` with the `windows: keys` command. ```javascript // Type text await driver.executeScript('windows: keys', [{ actions: [{text: 'Hello World'}] }]); ``` -------------------------------- ### Start Screen Recording (Windows Driver) Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Initiates screen recording on Windows. Requires FFMPEG to be installed and in PATH. The video is encoded with H264. ```powershell driver.executeScript("windows: startRecordingScreen", { videoFilter: "scale=ifnot(gte(iw\,1024)\,iw\,1024):-2", fps: 10, preset: "fast", captureCursor: true, captureClicks: true, timeLimit: 300, forceRestart: true }); ``` -------------------------------- ### Installing and Verifying FFmpeg for Screen Recording Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/errors.md Ensure FFmpeg is installed and accessible in the system's PATH for screen recording functionalities. Verify the installation using the 'ffmpeg -version' command. ```bash # Install FFmpeg # Download from https://ffmpeg.org/download.html # Add to PATH # Verify installation ffmpeg -version ``` -------------------------------- ### windowsStartRecordingScreen Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Starts recording the screen to an MP4 file using FFmpeg. Requires FFmpeg to be installed and in the system's PATH. ```APIDOC ## windowsStartRecordingScreen ### Description Start recording the screen to an MP4 file using FFmpeg. Requires FFmpeg installed and in PATH. ### Method async ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Optional - Recording options object - **videoFilter** (string) - Optional - FFmpeg video filter spec (e.g., `scale=1024:-2` to limit width) - **fps** (number) - Optional - Frames per second in output video. Defaults to 15. - **preset** (string) - Optional - Encoding preset: `ultrafast`, `superfast`, `veryfast`, `faster`, `fast`, `medium`, `slow`, `slower`, `veryslow`. Defaults to 'veryfast'. - **captureCursor** (boolean) - Optional - Whether to capture mouse cursor. Defaults to false. - **captureClicks** (boolean) - Optional - Whether to capture mouse clicks. Defaults to false. - **audioInput** (string) - Optional - DirectShow audio input device name. - **timeLimit** (number | string) - Optional - Maximum recording time in seconds (max 50s recommended). Defaults to 600. - **forceRestart** (boolean) - Optional - Whether to restart recording if already running. Defaults to true. ### Request Example ```typescript // Start basic recording await driver.windowsStartRecordingScreen(); // Start with custom settings await driver.windowsStartRecordingScreen({ fps: 20, preset: 'fast', captureCursor: true, captureClicks: true, timeLimit: 300, // 5 minutes }); // Limit video width to 1024px await driver.windowsStartRecordingScreen({ videoFilter: 'scale=ifnot(gte(iw\,1024)\,iw\,1024):-2', }); ``` ### Response #### Success Response None #### Response Example None ### Throws - Error: If FFmpeg is not found - Error: If another recording is running and forceRestart is false ``` -------------------------------- ### Verify FFmpeg Installation Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/configuration.md Ensure FFmpeg is installed and accessible in the system's PATH environment variable for screen recording functionality. ```bash ffmpeg -version # Verify installation ``` ```bash echo %PATH% # Check PATH includes FFmpeg directory ``` -------------------------------- ### Driver Method Invocation Examples Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Shows how to invoke extension commands using dedicated driver methods, which often provide a simpler syntax. ```javascript // JavaScript WebdriverIO await driver.windowsClick(undefined, 100, 200); ``` ```python # Python driver.windows_click(x=100, y=200) ``` ```java # Java driver.windowsClick(null, 100, 200, "left", null, null, 1, 100); ``` ```ruby # Ruby @driver.windows_click(nil, 100, 200) ``` ```csharp // C#/.NET driver.WindowsClick(null, 100, 200); ``` -------------------------------- ### WinAppDriver.start Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Starts the WinAppDriver server and creates a new session with the provided capabilities. It handles both built-in process startup and connection to an external server. ```APIDOC ## Method: WinAppDriver.start ### Description Start the WinAppDriver server and create a new session. ### Method Signature ```typescript async start(caps: WindowsDriverCaps): Promise ``` #### Parameters - **caps** (`WindowsDriverCaps`) - Required - Session capabilities with app/appTopLevelWindow #### Returns - `Promise` #### Throws - Error: If not running on Windows - Error: If port allocation fails - Error: If server startup times out - Error: If custom server URL is inaccessible - Error: If custom server responds with error #### Behavior 1. If `opts.url` provided: Connect to external server 2. Else: Start built-in WinAppDriver process 3. Create session with capabilities 4. Wait for server to respond to status requests 5. Store session ID in proxy #### Port Selection Details - If `opts.port` not set, auto-selects from range 4724-4824 - Uses file-based locking to prevent parallel conflicts - Times out after 5 seconds per lock attempt #### Startup Timeout Details - Waits up to 10000ms for server to respond - Retries every 1000ms - Checks with `/status` endpoint #### Example ```typescript const wad = new WinAppDriver(logger, {port: 4724}); await wad.start({ 'appium:app': 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App' }); // Server now running and session created ``` ``` -------------------------------- ### Execute Script Invocation Examples Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Demonstrates how to invoke extension commands using the `execute` or `executeScript` method across various programming languages. ```javascript // JavaScript WebdriverIO const result = await driver.execute('windows: click', [{ x: 100, y: 200 }]); ``` ```python # Python result = driver.execute_script('windows: click', { 'x': 100, 'y': 200 }) ``` ```java # Java driver.executeScript("windows: click", ImmutableMap.of( "x", 100, "y", 200 )); ``` ```ruby # Ruby @driver.execute_script('windows: click', {x: 100, y: 200}) ``` ```csharp // C#/.NET driver.ExecuteScript("windows: click", new Dictionary { {"x", 100}, {"y", 200} }); ``` -------------------------------- ### windows: startRecordingScreen Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Starts recording the screen in the background with various configurable options for video quality, cursor capture, and time limits. ```APIDOC ## windows: startRecordingScreen ### Description Start recording the screen in background. ### Method execute_script ### Endpoint windows: startRecordingScreen ### Parameters #### Request Body - **videoFilter** (string?) - Optional - FFmpeg filter spec (e.g., `scale=1024:-2`) - **fps** (number?) - Optional - Frames per second (1-60 recommended). Defaults to 15. - **preset** (string?) - Optional - Encoding: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow. Defaults to `'veryfast'`. - **captureCursor** (boolean?) - Optional - Include mouse cursor visualization. Defaults to false. - **captureClicks** (boolean?) - Optional - Highlight mouse clicks. Defaults to false. - **audioInput** (boolean?) - Optional - DirectShow audio device name. - **timeLimit** (number?) - Optional - Max recording time (seconds). Defaults to 600. - **forceRestart** (boolean?) - Optional - Restart if already recording. Defaults to true. ### Response #### Success Response (200) - **void** - No explicit return value. ### Throws - Error if FFmpeg not found/installed - Error if recording already running and forceRestart=false ### Example ```javascript // Via executeScript await driver.executeScript('windows: startRecordingScreen', [{ fps: 20, captureCursor: true, timeLimit: 300 }]); // Or via driver method (easier) await driver.windowsStartRecordingScreen({ fps: 20, captureCursor: true, timeLimit: 300 }); ``` ``` -------------------------------- ### Windows Get Clipboard Image Example Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Retrieves the Windows clipboard content as a base64-encoded PNG image. Specify 'image' for the contentType. ```json {"contentType": "image"} ``` -------------------------------- ### StartRecordingOptions Interface Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/types.md Defines the options for starting a screen recording. Use this to configure video filters, frame rate, encoding presets, and capture settings. ```typescript interface StartRecordingOptions { videoFilter?: string; fps?: number | string; preset?: string; captureCursor?: boolean; captureClicks?: boolean; audioInput?: string; timeLimit?: string | number; forceRestart?: boolean; } ``` -------------------------------- ### WADProcess.start Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Starts the WinAppDriver process. This method handles port auto-allocation, command-line argument building, and subprocess spawning. ```APIDOC ## start ### Description Start the WinAppDriver process. ### Method ```typescript async start(): Promise ``` ### Returns * `Promise` ### Throws * Error: If port allocation fails. * Error: If the executable path is invalid. ### Behavior 1. Auto-allocate port if not set (using file-based guard for parallelism). 2. Build command-line arguments. 3. Spawn subprocess with encoding 'ucs2'. 4. Log output to debug. 5. Register exit handler. 6. Register process ID for cleanup on exit. ### Command line `WinAppDriver.exe /wd/hub [/forcequit]` ### Example ```typescript const process = new WADProcess(logger, { base: '/wd/hub', executablePath: 'C:\\Program Files\\Windows Application Driver\\WinAppDriver.exe', isForceQuitEnabled: false }); await process.start(); console.log(`Started on port ${process.port}`); ``` ``` -------------------------------- ### Execute Windows-Specific Script (Dotnet) Source: https://github.com/appium/appium-windows-driver/blob/master/README.md This C# example demonstrates executing Windows-specific Appium commands. Arguments are passed within a Dictionary. ```csharp // Dotnet object result = driver.ExecuteScript("windows: ", new Dictionary() { {"arg1", "value1"}, {"arg2", "value2"} }); ``` -------------------------------- ### Close App Example (Appium Windows Driver) Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Demonstrates closing the active app window using both `executeScript` and the direct driver method. ```javascript await driver.executeScript('windows: closeApp'); // Or use driver method (easier) await driver.windowsCloseApp(); ``` -------------------------------- ### Get Available Contexts Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Retrieves a list of all available application contexts. For the Windows driver, this will always return ['NATIVE_APP']. ```typescript async getContexts(): Promise ``` -------------------------------- ### Stop Screen Recording Example (Appium Windows Driver) Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Shows how to stop screen recording and retrieve the video as base64 or upload it to a remote server with authentication. ```javascript // Get as base64 const base64Video = await driver.executeScript('windows: stopRecordingScreen'); // Upload to server await driver.executeScript('windows: stopRecordingScreen', [{ remotePath: 'https://myserver.com/upload/video.mp4', user: 'username', pass: 'password', method: 'POST' }]); ``` -------------------------------- ### Execute Set Clipboard to Text Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Example of setting the clipboard to plain text using `executeScript`. The text 'Hello' is Base64 encoded. ```javascript // Set text const text = Buffer.from('Hello').toString('base64'); await driver.executeScript('windows: setClipboard', [{ b64Content: text, contentType: 'plaintext' }]); ``` -------------------------------- ### Error Handling for Extension Commands Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Demonstrates how to wrap calls to extension commands in a try-catch block to handle potential errors gracefully. Includes examples for generic clicks and file deletion. ```javascript try { await driver.executeScript('windows: click', [{x: 100, y: 200}]); } catch (e) { console.log('Click failed:', e.message); } try { await driver.windowsDeleteFile('C:\\file.txt'); } catch (e) { if (e.message.includes('does not exist')) { console.log('File not found'); } } ``` -------------------------------- ### Windows Keys Action Example Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Use this to simulate customized keyboard input. It supports virtual key codes and text input. Ensure depressed keys are released. ```json [{"virtualKeyCode": 0x10, "down": true}, {"text": "appium likes you"}, {"virtualKeyCode": 0x10, "down": false}] ``` -------------------------------- ### Windows Set Clipboard Image Example Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Sets the Windows clipboard content to a base64-encoded PNG image. Specify 'image' for the contentType. ```json {"b64Content": "QXBwaXVm", "contentType": "image"} ``` -------------------------------- ### Execute windows: click with various options Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Shows examples of clicking an element, clicking at absolute coordinates with a specific button, and performing a double-click with modifier keys, including the equivalent driver method. ```javascript // Click element await driver.executeScript('windows: click', [{ elementId: 'element-id' }]); ``` ```javascript // Click absolute coordinates await driver.executeScript('windows: click', [{ x: 100, y: 200, button: 'right' }]); ``` ```javascript // Double-click with modifiers await driver.executeScript('windows: click', [{ x: 100, y: 200, times: 2, modifierKeys: ['ctrl', 'alt'] }]); ``` ```javascript // Or use driver method (easier) await driver.windowsClick('element-id', 100, 200, 'left', ['ctrl'], undefined, 2); ``` -------------------------------- ### Session Creation Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md After the WinAppDriver server has started, a new session is created by sending a POST request to the /session endpoint with W3C capabilities. ```APIDOC ## POST /session ### Description Creates a new session with the WinAppDriver server using W3C capabilities. ### Method POST ### Endpoint /session ### Parameters #### Request Body - **capabilities** (object) - Required - W3C capabilities object for the session. ### Response #### Success Response (200) - **sessionId** (string) - The ID of the created session. - **capabilities** (object) - The resolved capabilities for the session. ``` -------------------------------- ### Execute Windows-Specific Script (WebdriverIO) Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Invoke custom Windows-specific commands using the Appium driver in WebdriverIO. This example demonstrates passing arguments as an array of objects. ```javascript // WebdriverIO const result = await driver.executeScript('windows: ', [{ arg1: "value1", arg2: "value2", }]); ``` -------------------------------- ### Start WinAppDriver Process Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Initiates the WinAppDriver server process. This method handles port allocation, command-line argument construction, and subprocess spawning. Ensure the executable path is correct and the port is available. ```typescript async start(): Promise Start the WinAppDriver process. **Returns:** `Promise` **Throws:** - Error: If port allocation fails - Error: If executable path is invalid **Behavior:** 1. Auto-allocate port if not set (using file-based guard for parallelism) 2. Build command-line arguments 3. Spawn subprocess with encoding 'ucs2' 4. Log output to debug 5. Register exit handler 6. Register process ID for cleanup on exit **Command line:** `WinAppDriver.exe /wd/hub [/forcequit]` **Source:** `lib/winappdriver.ts:79-119` ``` ```typescript const process = new WADProcess(logger, { base: '/wd/hub', executablePath: 'C:\\Program Files\\Windows Application Driver\\WinAppDriver.exe', isForceQuitEnabled: false }); await process.start(); console.log(`Started on port ${process.port}`); ``` -------------------------------- ### Checking Platform Before Session Creation Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/errors.md Provides a code example to check if the operating system is Windows before attempting to create a session. This prevents the 'WinAppDriver tests only run on Windows' error. ```javascript // Check before creating session const os = require('os'); if (os.platform() !== 'win32') { throw new Error('This test requires Windows'); } ``` -------------------------------- ### createSession Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Creates a new test session for the WindowsDriver. This method validates the platform, executes prerun scripts, ensures DPI awareness, and starts the WinAppDriver server. ```APIDOC ## createSession ### Description Creates a new test session. Validates that platform is Windows, executes prerun scripts if provided, ensures DPI awareness, and starts the WinAppDriver server. ### Signature ```typescript async createSession( w3cCaps1: W3CWindowsDriverCaps, w3cCaps2?: W3CWindowsDriverCaps, w3cCaps3?: W3CWindowsDriverCaps, driverData?: DriverData[] ): Promise> ``` ### Parameters #### Parameters - **w3cCaps1** (`W3CWindowsDriverCaps`) - Required - Primary W3C capabilities object - **w3cCaps2** (`W3CWindowsDriverCaps`) - Optional - Secondary W3C capabilities (fallback) - **w3cCaps3** (`W3CWindowsDriverCaps`) - Optional - Tertiary W3C capabilities (fallback) - **driverData** (`DriverData[]`) - Optional - Data from other Appium drivers ### Returns `Promise<[sessionId: string, capabilities: WindowsDriverConstraints]>` ### Throws - Error: If not running on Windows - Error: If prerun script contains invalid format (missing 'script' or 'command' key) ### Example ```typescript const caps = { platformName: 'Windows', 'appium:automationName': 'Windows', 'appium:app': 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App', }; const [sessionId, capabilities] = await driver.createSession({ alwaysMatch: caps }); ``` ``` -------------------------------- ### WinAppDriver Command Line Arguments Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/configuration.md The WinAppDriver server process is started with specific arguments including port, base path, and an optional force quit flag. ```bash WinAppDriver.exe /wd/hub [/forcequit] ``` -------------------------------- ### WADProcess.port Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Gets the port number on which the WinAppDriver server is listening. This value is set during the start() method. ```APIDOC ## port ### Description The port the server is listening on. ### Property ```typescript port?: number ``` **Source:** `lib/winappdriver.ts:60` Set during `start()` via auto-allocation or from options. ``` -------------------------------- ### Python: Set up Windows Driver Session with Options Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Demonstrates how to configure WindowsOptions for different application types (UWP, classic executables) and how to initialize a WebDriver session. Ensure the correct app ID or path is used. ```python # Python3 + PyTest import pytest from appium import webdriver # Options are available in Python client since v2.6.0 from appium.options.windows import WindowsOptions def generate_options(): uwp_options = WindowsOptions() # How to get the app ID for Universal Windows Apps (UWP): # https://www.securitylearningacademy.com/mod/book/view.php?id=13829&chapterid=678 uwp_options.app = 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App' classic_options = WindowsOptions() classic_options.app = 'C:\\Windows\\System32\\notepad.exe' # Make sure arguments are quoted/escaped properly if necessary: # https://ss64.com/nt/syntax-esc.html classic_options.app_arguments = 'D:\\log.txt' classic_options.app_working_dir = 'D:\\' use_existing_app_options = WindowsOptions() # Active window handles could be retrieved from any compatible UI inspector app: # https://docs.microsoft.com/en-us/windows/win32/winauto/inspect-objects # or https://accessibilityinsights.io/. # Also, it is possible to use the corresponding WinApi calls for this purpose: # https://referencesource.microsoft.com/#System/services/monitoring/system/diagnosticts/ProcessManager.cs,db7ac68b7cb40db1 # # This capability could be used to create a workaround for UWP apps startup: # https://github.com/microsoft/WinAppDriver/blob/master/Samples/C%23/StickyNotesTest/StickyNotesSession.cs use_existing_app_options.app_top_level_window = hex(12345) return [uwp_options, classic_options, use_existing_app_options] @pytest.fixture(params=generate_options()) def driver(request): # The default URL is http://127.0.0.1:4723/wd/hub in Appium 1 drv = webdriver.Remote('http://127.0.0.1:4723', options=request.param) yield drv drv.quit() def test_app_source_could_be_retrieved(driver): assert len(driver.page_source) > 0 ``` -------------------------------- ### Execute Set Clipboard to Image Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Example of setting the clipboard to an image using `executeScript`. The image file 'screenshot.png' is read, Base64 encoded, and set as 'image' content type. ```javascript // Set image const img = require('fs').readFileSync('screenshot.png'); const b64Img = img.toString('base64'); await driver.executeScript('windows: setClipboard', [{ b64Content: b64Img, contentType: 'image' }]); ``` -------------------------------- ### Execute Complex Keyboard Sequence Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Example of a complex keyboard sequence involving typing text, pressing TAB, typing password, pausing, and pressing ENTER using `executeScript`. ```javascript // Complex sequence await driver.executeScript('windows: keys', [{ actions: [ {text: 'Username'}, {pause: 100}, {virtualKeyCode: 0x09}, // TAB {text: 'Password'}, {pause: 100}, {virtualKeyCode: 0x0D} // ENTER ] }]); ``` -------------------------------- ### Windows Get Clipboard Plaintext Example Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Retrieves the Windows clipboard content as base64-encoded plaintext. This is the default content type. ```json {} ``` -------------------------------- ### WinAppDriver.sendCommand Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Proxies a command to the WinAppDriver server, allowing direct interaction with the underlying WebDriver API. Supports GET, POST, PUT, and DELETE methods with optional request bodies. ```APIDOC ## Method: WinAppDriver.sendCommand ### Description Send a command to the WinAppDriver server via the proxy. ### Method Signature ```typescript async sendCommand(url: string, method: HTTPMethod, body?: HTTPBody): Promise ``` #### Parameters - **url** (`string`) - Required - API endpoint path (e.g., `/element`, `/screenshot`) - **method** (`'GET' | 'POST' | 'DELETE' | 'PUT'`) - Required - HTTP method - **body** (`any`) - Optional, Default: `null` - Request body JSON (null for GET/DELETE) #### Returns - `Promise` — Parsed JSON response from WinAppDriver #### Throws - `InvalidContextError`: If server process has exited - Error: If request fails or server returns error #### Example ```typescript // Find element const element = await wad.sendCommand('/element', 'POST', { using: 'accessibility id', value: 'btnOK' }); // Get element rect const rect = await wad.sendCommand(`/element/${element.ELEMENT}/rect`, 'GET'); // Click element await wad.sendCommand(`/element/${element.ELEMENT}/click`, 'POST', {}); ``` ``` -------------------------------- ### Enabling Debug Logging in Appium Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/architecture-overview.md Explains how to enable debug-level logging for Appium to get detailed diagnostic information. This is useful for troubleshooting and understanding the driver's internal operations. ```bash appium --log-level debug ``` -------------------------------- ### Fix Recording Already Running Error Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/errors.md When starting screen recording with forceRestart set to false and a recording is already active, either stop the existing recording first or use forceRestart=true. ```typescript await driver.windowsStopRecordingScreen(); await driver.windowsStartRecordingScreen(); // Or use forceRestart await driver.windowsStartRecordingScreen({forceRestart: true}); ``` -------------------------------- ### StartRecordingOptions Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/types.md Options for `windowsStartRecordingScreen()`. Allows configuration of video filters, frame rate, encoding presets, cursor and click capture, audio input, time limits, and restart behavior. ```APIDOC ## StartRecordingOptions ### Description Options for `windowsStartRecordingScreen()`. Allows configuration of video filters, frame rate, encoding presets, cursor and click capture, audio input, time limits, and restart behavior. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **videoFilter** (string) - Optional - FFmpeg filter spec (e.g., `scale=1024:-2`) - **fps** (number | string) - Optional - Frames per second. Defaults to `15`. - **preset** (string) - Optional - Encoding preset (ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow). Defaults to `'veryfast'`. - **captureCursor** (boolean) - Optional - Include mouse cursor in recording. Defaults to `false`. - **captureClicks** (boolean) - Optional - Highlight mouse clicks. Defaults to `false`. - **audioInput** (string) - Optional - DirectShow audio device name. - **timeLimit** (number | string) - Optional - Max recording time in seconds. Defaults to `600`. - **forceRestart** (boolean) - Optional - Restart if already recording. Defaults to `true`. ``` -------------------------------- ### WinAppDriver Server Startup Flow Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/architecture-overview.md Details the process of starting the WinAppDriver server, either by connecting to an external server or by spawning a new WinAppDriver.exe process. It covers port allocation, process monitoring, and server readiness checks. ```text WindowsDriver.createSession() ↓ WinAppDriver.start() ├─ If wadUrl provided: Connect to external server └─ Else: ├ WADProcess.start() │ ├ Auto-allocate port (with file lock guard) │ ├ Spawn WinAppDriver.exe process │ └ Monitor for exit ├ WADProxy creation └─ Wait for /status endpoint (10s timeout) ↓ Session created with capabilities ``` -------------------------------- ### Get Windows Clipboard Content Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Retrieves the Windows clipboard content as a base64-encoded string. Specify 'plaintext' or 'image' to get the desired content type. ```typescript async windowsGetClipboard(contentType?: 'plaintext' | 'image'): Promise ``` ```typescript // Get text from clipboard const b64Content = await driver.windowsGetClipboard('plaintext'); const text = Buffer.from(b64Content, 'base64').toString('utf8'); console.log(text); // Get image from clipboard const b64Img = await driver.windowsGetClipboard('image'); const buffer = Buffer.from(b64Img, 'base64'); await fs.writeFile('clipboard.png', buffer); ``` -------------------------------- ### Set and Get Clipboard with Supported Types Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/errors.md Use only the supported clipboard content types: 'plaintext' and 'image'. Providing unsupported types for setting or getting clipboard content will result in an error. ```typescript // Correct await driver.windowsSetClipboard(b64, 'plaintext'); await driver.windowsSetClipboard(b64, 'image'); await driver.windowsGetClipboard('plaintext'); await driver.windowsGetClipboard('image'); // Incorrect await driver.windowsSetClipboard(b64, 'video'); // Error ``` -------------------------------- ### Custom Server Connection Steps Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Steps to connect to a custom WinAppDriver server instance. This involves parsing the provided URL and verifying server responsiveness. ```text 1. Parse wadUrl to extract host/port/path 2. Create WADProxy with parsed URL 3. Verify server is responding with /status request 4. Continue if successful, error if not ``` -------------------------------- ### Instantiate WinAppDriver with Options Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-winappdriver.md Demonstrates how to create a new WinAppDriver instance with specified port and base path options. ```typescript const wad = new WinAppDriver(logger, { port: 4724, reqBasePath: '/wd/hub' }); ``` -------------------------------- ### Execute Hover Over Element Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Example of hovering over an element using `executeScript`. The `durationMs` parameter is set to 1000 milliseconds. ```javascript // Hover over element await driver.executeScript('windows: hover', [{ startElementId: 'element-id', durationMs: 1000 }]); ``` -------------------------------- ### Get Window Rectangle Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Retrieves the position and size of the application window. The position defaults to (0,0) if WinAppDriver cannot provide it. ```typescript const rect = await driver.getWindowRect(); console.log(`Window at (${rect.x},${rect.y}) size ${rect.width}x${rect.height}`); ``` -------------------------------- ### Get Current Context Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Retrieves the name of the currently active application context. For the Windows driver, this will always return 'NATIVE_APP'. ```typescript async getCurrentContext(): Promise ``` -------------------------------- ### Parameter Format for executeScript Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Illustrates the correct format for passing parameters to extension commands via `executeScript`. Parameters should be provided as a single object, not an array of values. ```javascript // Format: Single object as first argument await driver.executeScript('windows: methodName', [{ param1: value1, param2: value2 }]); // NOT an array of values // ✗ await driver.executeScript('windows: click', [100, 200]); // Wrong // ✓ await driver.executeScript('windows: click', [{x: 100, y:200}]); // Correct ``` -------------------------------- ### Get Element Rect Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Retrieves the bounding rectangle (position and size) of a specified UI element within the application window. ```typescript async getElementRect(elementId: string): Promise ``` -------------------------------- ### Get Proxy Avoid List Method Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Retrieves the list of routes that should not be proxied to WinAppDriver. These routes are handled directly by the driver. ```typescript getProxyAvoidList(sessionId: string): RouteMatcher[] ``` -------------------------------- ### Windows Set Clipboard Plaintext Example Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Sets the Windows clipboard content to the provided base64-encoded plaintext. This is the default content type. ```json {"b64Content": "QXBwaXVm"} ``` -------------------------------- ### Provide App Arguments Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/configuration.md Passes command-line arguments to the application on startup. Arguments must be properly quoted and escaped according to Windows shell rules. ```typescript opts.appArguments = 'C:\\Documents\\file.txt'; ``` ```typescript opts.appArguments = '/?'; // Help flag ``` -------------------------------- ### windows: stopRecordingScreen Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Stops the screen recording. If no recording was started, it returns an empty string. Supports uploading the video to a remote path. ```APIDOC ## windows: stopRecordingScreen ### Description Stop recording the screen. If no screen recording has been started before then the method returns an empty string. ### Method POST ### Endpoint /session/{sessionid}/appium/device/stop_recording_screen ### Parameters #### Query Parameters - **remotePath** (string) - Optional - The path to the remote location, where the resulting video should be uploaded. The following protocols are supported: http/https, ftp. Null or empty string value (the default setting) means the content of resulting file should be encoded as Base64 and passed as the endpoint response value. An exception will be thrown if the generated media file is too big to fit into the available process memory. Example: `https://myserver.com/upload/video.mp4` - **user** (string) - Optional - The name of the user for the remote authentication. Example: `myname` - **pass** (string) - Optional - The password for the remote authentication. Example: `mypassword` - **method** (string) - Optional - The http multipart upload method name. The 'PUT' one is used by default. Example: `POST` - **headers** (map) - Optional - Additional headers mapping for multipart http(s) uploads. Example: `{"header": "value"}` - **fileFieldName** (string) - Optional - The name of the form field, where the file content BLOB should be stored for http(s) uploads. `file` by default. Example: `payload` - **formFields** (Map or Array) - Optional - Additional form fields for multipart http(s) uploads. Example: `{"field1": "value1", "field2": "value2"}` or `[["field1", "value1"], ["field2", "value2"]]` ### Request Example ```json { "script": "windows: stopRecordingScreen", "args": [ { "remotePath": "https://myserver.com/upload/video.mp4", "user": "myname", "pass": "mypassword", "method": "POST", "headers": {"header": "value"}, "fileFieldName": "payload", "formFields": {"field1": "value1", "field2": "value2"} } ] } ``` ### Response #### Success Response (200) - **value** (string) - Base64-encoded content of the recorded media file if `remotePath` parameter is falsy or an empty string. ``` -------------------------------- ### WinAppDriverOptions Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/types.md Options for `WinAppDriver` class initialization. Configures the port, base request path, or a custom external server URL. ```APIDOC ## WinAppDriverOptions ### Description Options for `WinAppDriver` class initialization. Configures the port, base request path, or a custom external server URL. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **port** (number) - Optional - Port for WinAppDriver server. Auto-selected between 4724-4824 if not provided. - **reqBasePath** (string) - Optional - Base path for incoming requests. - **url** (string) - Optional - Custom external server URL (bypasses auto-start). ``` -------------------------------- ### windows: launchApp Source: https://github.com/appium/appium-windows-driver/blob/master/README.md Launches or relaunches the app under test in the same session. ```APIDOC ## POST /appium/windows/launchApp ### Description (Re)launches the app under test in the same session using the same capabilities configuration given on the session startup. This API generally creates a new app window and points the current active session to it, but the actual result may vary depending on how the actual application under test handles multiple instances creation. ### Method POST ### Endpoint /appium/windows/launchApp ### Parameters *No parameters are explicitly defined for this endpoint in the provided text.* ### Request Example *No request example is provided in the source text.* ### Response *No response details are provided in the source text.* ``` -------------------------------- ### Execute Drag and Drop with Coordinates Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Example of dragging an element to specific coordinates using `executeScript`. The `durationMs` parameter is set to 1000 milliseconds. ```javascript // Drag element to coordinates await driver.executeScript('windows: clickAndDrag', [{ startElementId: 'element-id', endX: 300, endY: 300, durationMs: 1000 }]); ``` -------------------------------- ### Launch App Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/api-reference-windows-driver.md Launches the app under test in the same session. Creates a new app window but does not automatically switch to it. Use switchWindow() to focus on the new window if needed. ```typescript await driver.windowsLaunchApp(); // Switch to new window if needed using switchWindow() ``` -------------------------------- ### Execute windows: deleteFolder with different paths Source: https://github.com/appium/appium-windows-driver/blob/master/_autodocs/extension-commands.md Demonstrates deleting a folder using the 'windows: deleteFolder' command with a specific path and the equivalent driver method. ```javascript await driver.executeScript('windows: deleteFolder', [{ remotePath: 'C:\\Users\\user\\tempdir' }]); ``` ```javascript // Or use driver method (easier) await driver.windowsDeleteFolder('C:\\path\\to\\folder'); ```