Skip to main content
Glama

webview_execute_js

Execute JavaScript within a Tauri app’s webview context to manipulate DOM, interact with app APIs, or retrieve data. Supports targeting specific windows or applications.

Instructions

[Tauri Apps Only] Execute JavaScript in a Tauri app's webview context. Requires active 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

  • Registration of the 'webview_execute_js' MCP tool. Defines its name, description, category (UI_AUTOMATION), schema (ExecuteJavaScriptSchema), and inline handler that delegates to executeJavaScript().
    {
       name: 'webview_execute_js',
       description:
          '[Tauri Apps Only] Execute JavaScript in a Tauri app\'s webview context. ' +
          'Requires active 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,
          });
       },
    },
  • ExecuteJavaScriptSchema: Zod schema for the webview_execute_js tool. Extends WindowTargetSchema with 'script' (required string) and 'args' (optional array of unknown values).
    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'),
    });
  • executeJavaScript() function: The core handler implementation. Wraps the script with args injection if args are provided, calls executeInWebviewWithContext(), and returns the result with window context info.
    export interface ExecuteJavaScriptOptions {
       script: string;
       args?: unknown[];
       windowId?: string;
       appIdentifier?: string | number;
    }
    
    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}`);
       }
    }
  • executeInWebviewWithContext(): Helper that performs the actual IPC execution. Sends the 'execute_js' command via WebSocket to the Tauri plugin bridge, parses the response, and returns the result with window label and optional warning.
    export async function executeInWebviewWithContext(
       script: string,
       windowId?: string,
       appIdentifier?: string | number
    ): Promise<ExecuteInWebviewResult> {
       try {
          // Ensure we're fully initialized
          await ensureReady(windowId, appIdentifier);
    
          // 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}`);
       }
    }
  • executeInWebview(): Simpler wrapper over executeInWebviewWithContext() that returns only the result string.
    export async function executeInWebview(script: string, windowId?: string, appIdentifier?: string | number): Promise<string> {
       const { result } = await executeInWebviewWithContext(script, windowId, appIdentifier);
    
       return result;
    }
Behavior5/5

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

Describes access to window.__TAURI__, JSON-serializable return requirement, IIFE syntax, and targeting logic. Contradicts no annotations.

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?

Four sentences, front-loaded purpose, no unnecessary words. Every sentence adds essential information.

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

Completeness5/5

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

Covers prerequisites, targeting, return values, and alternative tools. No output schema needed; description is self-sufficient for this complexity.

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

Parameters4/5

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

Schema covers all parameters, description adds value by clarifying defaults and targeting behavior, but schema already provides most semantic info.

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 it executes JavaScript in a Tauri webview, distinguishes from browser JS with a specific sibling reference (Chrome DevTools MCP), and includes prerequisites.

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?

Explicitly restricts to Tauri apps, requires active driver_session, and suggests an alternative for browser JS execution.

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