Skip to main content
Glama

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

TableJSON Schema
NameRequiredDescriptionDefault
windowIdNoWindow label to target (defaults to "main")
appIdentifierNoApp port or bundle ID to target. Defaults to the only connected app or the default app if multiple are connected.
scriptYesJavaScript 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; }"
argsNoArguments 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'),
    });
  • 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}`);
       }
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description adds valuable behavioral context beyond the annotations: it specifies that return values must be JSON-serializable, provides syntax guidance for IIFEs, and explains targeting logic for connected apps. While annotations cover basic hints (readOnlyHint=false, etc.), the description enriches understanding with practical constraints and execution details, though it doesn't mention rate limits or error handling.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is efficiently structured with zero waste: it front-loads the core purpose, then sequentially covers prerequisites, technical constraints, targeting behavior, and alternatives. Each sentence serves a distinct purpose, such as clarifying syntax or differentiating from other tools, making it highly concise and well-organized.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (executing JS in a specialized environment) and lack of output schema, the description provides strong contextual completeness: it covers prerequisites, return value constraints, targeting logic, and alternatives. However, it doesn't detail error cases or response formats, leaving minor gaps for a tool with no output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the input schema already documents all parameters thoroughly. The description reinforces key points about 'script' (JSON-serializable returns, IIFE syntax) and 'appIdentifier' (targeting logic), but doesn't add significant new semantic information beyond what's in the schema. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Execute JavaScript') and resource ('in a Tauri app's webview context'), distinguishing it from siblings like 'tauri_webview_interact' or 'tauri_webview_find_element' which perform different webview operations. It explicitly mentions the Tauri-specific context and access to window.__TAURI__, making the purpose distinct and well-defined.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool vs. alternatives: it states '[Tauri Apps Only]' and 'For browser JS execution, use Chrome DevTools MCP instead.' It also specifies prerequisites ('Requires active tauri_driver_session') and clarifies targeting behavior ('Targets the only connected app, or the default app if multiple are connected'), offering clear context for usage decisions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/hypothesi/mcp-server-tauri'

If you have feedback or need assistance with the MCP directory API, please join our Discord server