tauri_webview_execute_js
Execute JavaScript code within Tauri application webviews to automate UI interactions, access Tauri APIs, and retrieve JSON-serializable return values for testing and debugging purposes.
Instructions
[Tauri Apps Only] Execute JavaScript in a Tauri app's webview context. Requires active tauri_driver_session. Has access to window.TAURI. If you need a return value, it must be JSON-serializable. For functions that return values, use an IIFE: "(() => { return 5; })()" not "() => { return 5; }". Targets the only connected app, or the default app if multiple are connected. Specify appIdentifier (port or bundle ID) to target a specific app. For browser JS execution, use Chrome DevTools MCP instead.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| windowId | No | Window label to target (defaults to "main") | |
| appIdentifier | No | App port or bundle ID to target. Defaults to the only connected app or the default app if multiple are connected. | |
| script | Yes | JavaScript code to execute in the webview context. If returning a value, it must be JSON-serializable. For functions that return values, use IIFE syntax: "(() => { return value; })()" not "() => { return value; }" | |
| args | No | Arguments to pass to the script |
Implementation Reference
- Main handler function for the tool. Parses options, wraps script with arguments if provided, executes via webview executor, formats result with window context and warnings.export async function executeJavaScript(options: ExecuteJavaScriptOptions): Promise<string> { const { script, args, windowId, appIdentifier } = options; // If args are provided, we need to inject them into the script context const wrappedScript = args && args.length > 0 ? ` (function() { const args = ${JSON.stringify(args)}; return (${script}).apply(null, args); })(); ` : script; try { const { result, windowLabel, warning } = await executeInWebviewWithContext(wrappedScript, windowId, appIdentifier); // Build response with window context let response = result; if (warning) { response = `⚠️ ${warning}\n\n${response}`; } // Add window info footer for clarity response += `\n\n[Executed in window: ${windowLabel}]`; return response; } catch(error: unknown) { const message = error instanceof Error ? error.message : String(error); throw new Error(`JavaScript execution failed: ${message}`); } }
- Zod input schema for the tool, extending WindowTargetSchema with script (required string) and optional args array.export const ExecuteJavaScriptSchema = WindowTargetSchema.extend({ script: z.string().describe( 'JavaScript code to execute in the webview context. ' + 'If returning a value, it must be JSON-serializable. ' + 'For functions that return values, use IIFE syntax: "(() => { return value; })()" not "() => { return value; }"' ), args: z.array(z.unknown()).optional().describe('Arguments to pass to the script'), });
- packages/mcp-server/src/tools-registry.ts:449-476 (registration)Tool definition and registration in the central TOOLS array, including description, annotations, schema reference, and handler that parses input and delegates to executeJavaScript.{ name: 'tauri_webview_execute_js', description: '[Tauri Apps Only] Execute JavaScript in a Tauri app\'s webview context. ' + 'Requires active tauri_driver_session. Has access to window.__TAURI__. ' + 'If you need a return value, it must be JSON-serializable. ' + 'For functions that return values, use an IIFE: "(() => { return 5; })()" not "() => { return 5; }". ' + MULTI_APP_DESC + ' ' + 'For browser JS execution, use Chrome DevTools MCP instead.', category: TOOL_CATEGORIES.UI_AUTOMATION, schema: ExecuteJavaScriptSchema, annotations: { title: 'Execute JS in Tauri Webview', readOnlyHint: false, destructiveHint: false, openWorldHint: false, }, handler: async (args) => { const parsed = ExecuteJavaScriptSchema.parse(args); return await executeJavaScript({ script: parsed.script, args: parsed.args, windowId: parsed.windowId, appIdentifier: parsed.appIdentifier, }); }, },
- Core helper that performs the actual WebSocket command 'execute_js' to the Tauri plugin, handles response parsing, window context, and errors.export async function executeInWebviewWithContext( script: string, windowId?: string, appIdentifier?: string | number ): Promise<ExecuteInWebviewResult> { try { // Ensure we're fully initialized await ensureReady(); // Resolve target session const session = resolveTargetApp(appIdentifier); const client = session.client; // Send script directly - Rust handles wrapping and IPC callbacks. // Use 7s timeout (longer than Rust's 5s) so errors return before Node times out. const response = await client.sendCommand({ command: 'execute_js', args: { script, windowLabel: windowId }, }, 7000); if (!response.success) { throw new Error(response.error || 'Unknown execution error'); } // Extract window context from response const windowContext = response.windowContext; // Parse and return the result const data = response.data; let result: string; if (data === null || data === undefined) { result = 'null'; } else if (typeof data === 'string') { result = data; } else { result = JSON.stringify(data); } return { result, windowLabel: windowContext?.windowLabel || 'main', warning: windowContext?.warning, }; } catch(error: unknown) { const message = error instanceof Error ? error.message : String(error); throw new Error(`WebView execution failed: ${message}`); } }