# Using JavaScript for Profile Enhancement and Scripting in Clash Verge Rev

> Enhance Clash Verge Rev profiles with JavaScript scripting. Automate proxy configuration beyond static files in a secure sandbox environment. Learn how now.

- Repository: [Clash Verge Rev/clash-verge-rev](https://github.com/clash-verge-rev/clash-verge-rev)
- Tags: how-to-guide
- Published: 2026-02-27

---

**Clash Verge Rev enables dynamic profile manipulation through JavaScript snippets that execute in a sandboxed environment, allowing automated proxy configuration beyond static YAML files.**

Clash Verge Rev is a modern GUI client for Clash built with **React**, **TypeScript**, and **Tauri**. The application supports **JavaScript for profile enhancement and scripting**, allowing users to programmatically manipulate YAML configurations, create dynamic proxy groups, and automate routing rules at runtime.

## Architecture of JavaScript Profile Scripting

The profile scripting system spans both the frontend React layer and the Rust backend, connected through Tauri's command bridge.

### Frontend Stack and Data Flow

The UI layer manages profile state using **SWR** for caching and real-time updates. Key architectural components include:

- **[`src/pages/profiles.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/pages/profiles.tsx)** – Main profile list UI, batch actions, and the "Reactivate" button that triggers script re-enhancement
- **[`src/hooks/use-profiles.ts`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/hooks/use-profiles.ts)** – Centralized `useProfiles` hook managing profile activation and state mutations
- **[`src/services/cmds.ts`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/services/cmds.ts)** – Tauri command wrappers including `enhanceProfiles`, `viewProfile`, and `saveProfileFile`
- **[`src/components/profile/profile-more.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/components/profile/profile-more.tsx)** – "More" menu hosting the Script editor interface

### Backend Integration with Tauri

The Rust backend (exposed via `invoke` calls) handles the actual script execution:

- **`enhance_profiles`** – Validates and executes JavaScript in a sandboxed environment, then merges modifications back into the runtime configuration
- **`view_profile`** – Opens the script file in the OS default editor (e.g., VS Code)
- **`patch_profile`** – Persists script-generated proxy selections to disk

## Profile Enhancement Flow

Understanding the execution pipeline helps debug script behavior and optimize performance.

### The Script Execution Pipeline

When a user clicks **"Reactivate"** or saves a script file, the following sequence occurs:

1. **Trigger** – `enhanceProfiles()` invokes the Rust command `enhance_profiles`
2. **Execution** – The backend reads the profile's JavaScript snippet and executes it in a sandbox
3. **Modification** – The script can modify proxy groups, add rules, or manipulate the configuration object
4. **Persistence** – `patchProfile` saves the enhanced configuration
5. **Activation** – `activateSelected` applies the new proxy selections to the runtime

### From Editor to Runtime

The UI provides two editing modes for JavaScript scripts:

**In-App Editor** (`EditorViewer` component in [`profile-more.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/profile-more.tsx)):

```typescript
<EditorViewer
  open={true}
  title="Script"
  initialData={() => readProfileFile("Script")}
  dataKey="Script"
  language="javascript"
  onSave={async (prev, curr) => {
    await saveProfileFile("Script", curr ?? "");
    // Trigger re-enhancement after save
    await enhanceProfiles();
  }}
/>

```

**External Editor** via `viewProfile`:

```typescript
// Opens the script file in system default editor (VS Code, etc.)
await viewProfile("Script");

```

## Key Implementation Details

### Managing Profile State with useProfiles

The `useProfiles` hook in [`src/hooks/use-profiles.ts`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/hooks/use-profiles.ts) centralizes all profile operations:

```typescript
export const useProfiles = () => {
  const { data: profiles, mutate: mutateProfiles } = useSWR(
    "getProfiles", 
    getProfiles, 
    { revalidateOnFocus: false, dedupingInterval: 500 }
  );

  const activateSelected = async (profileOverride?: IProfilesConfig) => {
    // 1. Calculate proxy tree
    const proxiesData = await calcuProxies();
    // 2. Read saved selections
    // 3. Apply changes via selectNodeForGroup (Rust)
    // 4. Persist with patchProfile
  };

  return {
    profiles,
    current: profiles?.items?.find(p => p?.uid === profiles.current),
    activateSelected,
    mutateProfiles,
  };
};

```

### Command Bridge to Rust Backend

The [`src/services/cmds.ts`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/services/cmds.ts) file provides typed wrappers around Tauri commands:

```typescript
// Execute profile enhancement (runs JavaScript scripts)
export async function enhanceProfiles() {
  return invoke<void>("enhance_profiles");
}

// Open profile file in external editor
export async function viewProfile(index: "Merge" | "Script" | "Rules") {
  return invoke<void>("view_profile", { index });
}

// Save file content back to backend
export async function saveProfileFile(index: string, content: string) {
  return invoke<void>("save_profile_file", { index, content });
}

// Update profile configuration
export async function patchProfiles(
  profile: Partial<IProfilesConfig>, 
  signal?: AbortSignal,
  options?: { deferRefreshOnSuccess?: boolean }
) {
  return invoke<void>("patch_profiles", { profile }, { signal });
}

```

### UI Components for Script Management

The `ProfileMore` component in [`src/components/profile/profile-more.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/components/profile/profile-more.tsx) handles the script editing interface:

```typescript
const ProfileMore = ({ id, onSave }: Props) => {
  const onOpenFile = useLockFn(async () => {
    try {
      await viewProfile(id); // Open in system editor
    } catch (err) {
      showNotice.error(err);
    }
  });

  return (
    <EditorViewer
      language={id === "Merge" ? "yaml" : "javascript"}
      onSave={async (prev, curr) => {
        await saveProfileFile(id, curr ?? "");
        onSave?.(prev, curr); // Trigger UI refresh
      }}
    />
  );
};

```

## Handling Concurrent Profile Switches

When users rapidly switch between profiles or click "Reactivate" multiple times, the application must prevent race conditions and ensure only the latest request takes effect.

### AbortController Implementation

The [`profiles.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/profiles.tsx) page implements request sequencing using React refs:

```typescript
const requestSequenceRef = useRef<number>(0);
const abortControllerRef = useRef<AbortController | null>(null);

const activateProfile = useCallback(async (profile, notifySuccess) => {
  const currentSequence = ++requestSequenceRef.current;
  const currentAbortController = new AbortController();
  abortControllerRef.current = currentAbortController;

  try {
    const requestPromise = patchProfiles(
      { current: profile },
      currentAbortController.signal,
      { deferRefreshOnSuccess: true }
    );
    
    // ... wait for promise
    
    // Discard if outdated or aborted
    if (isRequestOutdated(currentSequence, requestSequenceRef, profile) ||
        isOperationAborted(currentAbortController, profile)) {
      return;
    }
    
    await activateSelected();
  } catch (e) {
    if (e.name === "AbortError") return; // Expected abort
    throw e;
  }
}, [patchProfiles, activateSelected]);

```

### Request Sequencing

The `isRequestOutdated` check compares the sequence number captured at the start of the function against the current ref value. If they differ, a newer request has started, and the current one should be discarded. This prevents stale script executions from overwriting newer configurations.

## Code Examples

### Writing and Saving a Custom Script

This example demonstrates the complete workflow for adding a JavaScript enhancement script to a profile:

```typescript
import { useProfiles } from "@/hooks/use-profiles";
import { viewProfile, saveProfileFile, enhanceProfiles } from "@/services/cmds";
import { showNotice } from "@/services/notice-service";

async function addCustomScript(profileUid: string, code: string) {
  try {
    // Optional: Open external editor for convenience
    await viewProfile("Script");
    
    // Persist the JavaScript code
    await saveProfileFile("Script", code);
    
    // Trigger backend execution of the script
    await enhanceProfiles();
    
    // Refresh UI state to reflect changes
    const { mutateProfiles } = useProfiles();
    await mutateProfiles();
    
    showNotice.success("Script saved and profile enhanced");
  } catch (e) {
    showNotice.error(e);
  }
}

```

*Reference*: The `enhanceProfiles` command is defined in [[`src/services/cmds.ts`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/services/cmds.ts)](https://github.com/clash-verge-rev/clash-verge-rev/blob/dev/src/services/cmds.ts).

### Monitoring Script Execution Logs

Scripts run in a sandboxed environment, but errors and logs are captured and displayed in the UI:

```typescript
import { useEffect } from "react";
import { getRuntimeLogs } from "@/services/cmds";
import useSWR from "swr";

function ScriptLogViewer() {
  const { data: logs = [] } = useSWR("getRuntimeLogs", getRuntimeLogs);

  useEffect(() => {
    const hasError = logs.some(([level]) => level === "exception");
    if (hasError) {
      showNotice.error("Script execution failed – see Log Viewer");
    }
  }, [logs]);

  return (
    <LogViewer 
      open={true} 
      logInfo={logs} 
      onClose={() => {}} 
    />
  );
}

```

*Reference*: The `LogViewer` component is utilized within `ProfileMore` at [[`src/components/profile/profile-more.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/components/profile/profile-more.tsx)](https://github.com/clash-verge-rev/clash-verge-rev/blob/dev/src/components/profile/profile-more.tsx).

### Safe Profile Switching with Abort Support

When implementing custom profile switchers, handle race conditions using the same pattern as the main application:

```typescript
import { useRef } from "react";
import { patchProfiles, activateSelected } from "@/services/cmds";

function useSafeProfileSwitcher() {
  const requestSeq = useRef(0);
  const abortCtrl = useRef<AbortController | null>(null);

  const switchProfile = async (uid: string) => {
    const seq = ++requestSeq.current;
    
    // Cancel any pending request
    abortCtrl.current?.abort();
    const controller = new AbortController();
    abortCtrl.current = controller;

    try {
      await patchProfiles({ current: uid }, controller.signal);
      
      // Discard result if newer request started while waiting
      if (seq !== requestSeq.current) return;
      
      await activateSelected();
    } catch (e) {
      if (e.name === "AbortError") return; // Expected
      console.error("Profile switch failed:", e);
    }
  };

  return { switchProfile };
}

```

*Reference*: The production implementation resides in `ProfilePage.activateProfile` within [[`src/pages/profiles.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/pages/profiles.tsx)](https://github.com/clash-verge-rev/clash-verge-rev/blob/dev/src/pages/profiles.tsx).

## Summary

- **JavaScript profile enhancement** in Clash Verge Rev allows dynamic manipulation of proxy configurations through sandboxed scripts stored per-profile.
- The **enhancement pipeline** follows a strict sequence: script editing via `saveProfileFile`, backend execution via `enhanceProfiles`, and UI refresh via `mutateProfiles`.
- **Race condition protection** is implemented using `AbortController` and request sequencing in [`src/pages/profiles.tsx`](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src/pages/profiles.tsx) to ensure only the latest profile switch takes effect.
- Scripts are stored in the Tauri runtime directory and accessible through the **Script** slot in the `ProfileMore` component, with logs available via `getRuntimeLogs`.

## Frequently Asked Questions

### How do I execute a JavaScript script after editing it in Clash Verge Rev?

After saving your script via `saveProfileFile("Script", code)`, you must call `enhanceProfiles()` to trigger the backend execution. The Rust backend then runs your JavaScript in a sandboxed environment, applies any modifications to the proxy configuration, and persists the changes. Finally, call `mutateProfiles()` to refresh the UI state and reflect the enhanced configuration.

### What is the difference between Merge and Script modes in profile enhancement?

**Merge** mode accepts YAML syntax and performs static merging of configuration keys, useful for overriding specific values without logic. **Script** mode accepts JavaScript and enables dynamic logic, allowing you to programmatically generate proxy groups, filter nodes based on latency tests, or modify rules at runtime based on external conditions. The UI distinguishes these via the `language` prop in `EditorViewer`, passing `"yaml"` for Merge and `"javascript"` for Script.

### Where are the JavaScript enhancement scripts physically stored?

Script files are stored in the Tauri runtime directory under the profile's unique identifier. When you call `viewProfile("Script")`, the backend resolves the path to the specific script file associated with the current profile and opens it in the OS default editor. The `saveProfileFile` command writes content back to this location, ensuring persistence across application restarts.

### How does Clash Verge Rev prevent race conditions when switching profiles rapidly?

The application implements a request sequencing pattern using React refs (`requestSequenceRef`) and `AbortController`. Each profile switch increments a sequence number and creates a new `AbortController`. If a new switch occurs while a previous one is pending, the previous controller is aborted and the sequence number mismatch causes the stale promise's results to be discarded. This ensures only the most recent profile activation—and its associated JavaScript enhancement—takes effect.