> ## Documentation Index
> Fetch the complete documentation index at: https://docs.phones.farm/llms.txt
> Use this file to discover all available pages before exploring further.

# Script Integration

> Embedding custom automation workflows, scheduling cron jobs, and chaining multi-device API pipelines.

## 1.Overview

iClick has a built-in **lightweight script management system**.

Through script extensions, you can:

* 🎯 **Add Custom Buttons** - Add quick action buttons to the console header
* 📋 **Extend Context Menu** - Add exclusive context menus for devices
* 🔧 **Call External Programs** - Launch your automation tools with one click
* 🌐 **Integrate Web Interface** - Embed your management panel in iClick

💡 Script Package Format

iClick console supports importing script packages with `.isx` extension. Currently, `.isx` files are essentially **ZIP archives** that you can pack using any compression tool.

### 📦 Script Structure

Each script extension is an independent folder containing configuration files and resources:

```
com.example.myscript/          # Script package directory
├── manifest.json               # Configuration manifest (required)
├── icon.png                    # Script icon (optional)
├── more files
```

**Core Files:**

| File | Required | Description |
| - | - | - |
| `manifest.json` | ✅ | Script configuration manifest, defining metadata and behavior |
| `icon.png` | Recommended | Script icon displayed in console |
| Other files | Optional | External programs, config files, resources, etc. |

## 2.Manifest File (manifest.json)

`manifest.json` is the core configuration file for script extensions, defining basic information, tasks, UI extensions, and settings.

### File Structure Overview

A complete `manifest.json` contains the following sections:

```
{
  // Basic information (required)
  "id": "com.example.myscript",
  "name": "Script Name",
  "version": "1.0.0",
  "author": "Author",
  
  // Event listeners (optional)
  "events": {...},
  
  // Task definitions (optional)
  "scripts": [...],
  
  // UI extensions (optional)
  "views": {...},
  
  // Settings panel (optional)
  "settings": [...]
}
```

***

### 1. Basic Information

Every script package must contain basic information fields:

```
{
  "id": "com.example.myscript",
  "name": "My Script",
  "version": "1.0.0",
  "author": "Your Name",
  "description": "Script description",
  "icon": "icon.png"
}
```

#### Field Description

| Field | Type | Required | Description |
| - | - | - | - |
| `id` | string | ✅ | Unique script identifier, recommend reverse domain format (e.g., `com.company.product`) |
| `name` | string | ✅ | Script display name |
| `version` | string | ✅ | Version number, recommend semantic versioning (e.g., `1.0.0`) |
| `author` | string | ✅ | Author name |
| `description` | string | Optional | Script description |
| `icon` | string | Optional | Icon path, supports relative path or HTTP URL |

***

### 2. Event Listeners (events)

Define listeners and handlers for application lifecycle events.

#### Basic Example

```
{
  "events": {
    "app/run": {
      "action": "$.nodejs.run",
      "args": ["server.js", "arg1", "arg2"]
    }
  }
}
```

#### Supported Event Types

| Event | Description | Trigger Timing |
| - | - | - |
| `app/run` | Application start event | After iClick app launches |

#### Field Description

| Field | Type | Required | Description |
| - | - | - | - |
| Event name | object | ✅ | Event handler object (e.g., `app/run`) |
| `action` | string | ✅ | Command action type |
| `args` | array | ✅ | Command arguments array |

#### Use Cases

* **app/run**: Start background services, initialize data, load configurations, etc.

***

### 3. Task Definition (scripts)

Define executable tasks in the context menu.

#### Basic Example

```
{
  "scripts": [
    {
      "id": "open_tool",
      "name": "Open Tool",
      "command": {
        "action": "$.shell.open",
        "args": ["Tool.exe", "$.deviceId"]
      }
    },
    {
      "id": "sync_data",
      "name": "Sync Data",
      "command": {
        "action": "$.http.post",
        "args": [
          "https://api.example.com/sync",
          { "deviceId": "$.deviceId" }
        ]
      }
    }
  ]
}
```

#### Field Description

| Field | Type | Required | Description |
| - | - | - | - |
| `id` | string | ✅ | Unique task identifier |
| `name` | string | ✅ | Task display name, shown in context menu |
| `batch` | string | ❌ | Is it integrated into the batch operation menu |
| `command` | object | ✅ | Command object |
| `command.action` | string | ✅ | Command action type |
| `command.args` | array | ✅ | Command arguments array |

***

### 4. UI Extensions (views)

Add custom buttons to the console interface.

#### Basic Example

```
{
  "views": {
    "header/slots": [
      {
        "name": "Dashboard",
        "icon": "dashboard.png",
        "command": {
          "action": "$.webview.open",
          "args": [
            "https://dashboard.example.com/",
            { "width": 1200, "height": 800 }
          ]
        }
      }
    ]
  }
}
```

#### Supported Slot Positions

| Slot Position | Description |
| - | - |
| `header/slots` | Console header button area |

#### Field Description

| Field | Type | Required | Description |
| - | - | - | - |
| `name` | string | ✅ | Button display name |
| `icon` | string | ✅ | Button icon path |
| `command` | object | ✅ | Command object |

***

### 5. Settings Panel (settings)

Add visual configuration forms for scripts. After saving, a `settings.json` file will be automatically generated in the script directory.

#### Supported Configuration Types

| Type | Description |
| - | - |
| `text` | Single-line text input |
| `number` | Number input |
| `checkbox` | Checkbox |
| `select` | Dropdown select |
| `textarea` | Multi-line text |
| `file` | File selector |
| `path` | Folder selector |
| `date` | Date picker |
| `time` | Time picker |
| `datetime` | Datetime picker |

📖 Detailed Documentation

See [Settings Panel](#settings-panel-settings) for complete configuration types, field definitions, reading methods, and best practices.

***

### Related Documentation

* Script Integration Overview - Learn about script extension mechanism
* Operations - Command syntax and usage
* Settings Panel - Detailed settings documentation
* Complete Examples - Real-world scenario examples
* [API Reference]() - WebSocket API documentation

## 3.Operations

Operations define the specific actions that scripts will execute. The same instruction structure is used in both task definitions (`scripts`) and UI extensions (`views`).

### Instruction Structure

All operations contain two required fields:

```
{
  "command": {
    "action": "operation_type",
    "args": ["param1", "param2", ...]
  }
}
```

| Field | Type | Required | Description |
| - | - | - | - |
| `action` | string | ✅ | Operation type |
| `args` | array | ✅ | Operation arguments array |

***

### Supported Operation Types

iClick supports 5 operation types:

| Operation | Purpose | Use Cases |
| - | - | - |
| `$.nodejs.run` | Execute Node.js scripts | Run NODE scripts |
| `$.shell.open` | Execute external programs | Launch exe, open files |
| `$.http.get` | HTTP GET request | Call APIs |
| `$.http.post` | HTTP POST request | Call APIs |
| `$.webview.open` | Open WebView window | Display web management interface |

***

### \$.nodejs.run

Execute Node.js script files.

#### Syntax

```
{
  "action": "$.nodejs.run",
  "args": ["script_path", "param1", "param2", ...]
}
```

#### Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `args[0]` | string | ✅ | Node.js script path |
| `args[1+]` | string | Optional | Script parameters |

#### Path Rules

* **Relative path**: Relative to script package directory

  ```
  "args": ["script.js", "arg1"]
  // Actual path: %APPDATA%/iClick/Scripts/ScriptID/script.js
  ```
* **Absolute path**: Full file path

  ```
  "args": ["C:\\Users\\Admin\\scripts\\task.js", "arg1"]
  ```

***

### \$.shell.open

Execute external programs or open files.

#### Syntax

```
{
  "action": "$.shell.open",
  "args": ["program_path", "param1", "param2", ...]
}
```

#### Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `args[0]` | string | ✅ | Program path |
| `args[1+]` | string | Optional | Command line arguments |

#### Path Rules

* **Relative path**: Relative to script package directory

  ```
  "args": ["Tool.exe", "arg1"]
  // Actual path: %APPDATA%/iClick/Scripts/ScriptID/Tool.exe
  ```
* **Absolute path**: Full file path

  ```
  "args": ["C:\\Program Files\\MyApp\\app.exe", "arg1"]
  ```

***

### \$.http.get

Send HTTP GET request.

#### Syntax

```
{
  "action": "$.http.get",
  "args": ["URL", {query_params}, {headers}]
}
```

#### Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `args[0]` | string | ✅ | Request URL |
| `args[1]` | object | Optional | Query parameters object |
| `args[2]` | object | Optional | Request headers object |

***

### \$.http.post

Send HTTP POST request.

#### Syntax

```
{
  "action": "$.http.post",
  "args": ["URL", {request_body}, {headers}]
}
```

#### Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `args[0]` | string | ✅ | Request URL |
| `args[1]` | object | Optional | Request body object |
| `args[2]` | object | Optional | Request headers object |

***

### \$.webview\.open

Open embedded WebView window.

#### Syntax

```
{
  "action": "$.webview.open",
  "args": ["URL", {window_options}]
}
```

#### Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `args[0]` | string | ✅ | URL address |
| `args[1]` | object | Optional | Window options object |

#### Window Options

| Option | Type | Default | Description |
| - | - | - | - |
| `width` | number | 800 | Window width (pixels) |
| `height` | number | 600 | Window height (pixels) |
| `alwaysOnTop` | boolean | false | Always on top |
| `resizable` | boolean | true | Resizable |
| `maximizable` | boolean | true | Maximizable |
| `minimizable` | boolean | true | Minimizable |
| `maxWidth` | number | - | Maximum width |
| `maxHeight` | number | - | Maximum height |

***

### Magic Variables

You can use magic variables in operation parameters (e.g., in context menus), which will be automatically replaced with actual values at runtime.

#### Available Variables

| Variable | Description | Example Value |
| - | - | - |
| `$.deviceId` | Currently selected device ID | `"iPhone-12345"` |

#### Use Cases

Magic variables are particularly useful for scenarios that require current context information:

## 4.Settings Panel (settings)

The settings panel allows you to add visual configuration forms for scripts. Users can easily modify these settings in the iClick console without manually editing configuration files.

### Basic Usage

Add `settings` field in `manifest.json`:

```
{
  "settings": [
    {
      "key": "api_url",
      "name": "API Address",
      "type": "text",
      "value": "https://api.example.com",
      "placeholder": "Enter API address",
      "require": true
    }
  ]
}
```

### Common Field Description

Each configuration item supports the following fields:

| Field | Type | Required | Description |
| - | - | - | - |
| `key` | string | ✅ | Unique configuration identifier, used to read config values in programs |
| `name` | string | ✅ | Configuration display name, shown in configuration form |
| `type` | string | ✅ | Configuration type (see type list below) |
| `value` | any | ✅ | Default value, type should match `type` |
| `placeholder` | string | Optional | Input placeholder text |
| `require` | boolean | Optional | Whether required, default `false` |

### Configuration Types

#### text - Single-line Text Input

Suitable for short text input, such as API Key, URL, etc.

```
{
  "key": "api_key",
  "name": "API Key",
  "type": "text",
  "value": "",
  "placeholder": "Enter your API key",
  "require": true
}
```

**Use Cases:**

* API keys
* URLs
* Usernames
* Short text configuration

***

#### number - Number Input

Suitable for number input, such as port numbers, timeout values, etc.

```
{
  "key": "timeout",
  "name": "Timeout (seconds)",
  "type": "number",
  "value": 30,
  "placeholder": "Enter timeout in seconds"
}
```

**Use Cases:**

* Timeout values
* Port numbers
* Quantity limits
* Time intervals

***

#### checkbox - Checkbox

Suitable for boolean (on/off) options.

```
{
  "key": "enable_log",
  "name": "Enable Logging",
  "type": "checkbox",
  "value": true
}
```

**Use Cases:**

* Feature toggles
* Enable/disable options
* Debug mode switches

***

#### select - Dropdown Select

Suitable for selecting one value from predefined options.

```
{
  "key": "mode",
  "name": "Run Mode",
  "type": "select",
  "value": "auto",
  "options": [
    { "label": "Auto Mode", "value": "auto" },
    { "label": "Manual Mode", "value": "manual" },
    { "label": "Debug Mode", "value": "debug" }
  ]
}
```

**Special Fields:**

* `options`: Options array, each option contains `label` (display text) and `value` (actual value)

**Use Cases:**

* Run mode selection
* Log levels
* Theme selection
* Language selection

***

#### textarea - Multi-line Text

Suitable for long text or multi-line content input.

```
{
  "key": "config_content",
  "name": "Config File Content",
  "type": "textarea",
  "value": "",
  "placeholder": "Enter config file content (JSON or other format)"
}
```

**Use Cases:**

* Configuration file content
* Script code
* Long text descriptions
* JSON configuration

***

#### file - File Selector

Allows users to select a file.

```
{
  "key": "cert_file",
  "name": "Certificate File",
  "type": "file",
  "value": "",
  "placeholder": "Select certificate file"
}
```

**Use Cases:**

* Certificate files
* Configuration files
* Data files
* Image files

***

#### path - Folder Selector

Allows users to select a folder path.

```
{
  "key": "output_dir",
  "name": "Output Directory",
  "type": "path",
  "value": "",
  "placeholder": "Select output directory"
}
```

**Use Cases:**

* Output directories
* Working directories
* Data storage paths
* Log directories

***

#### date - Date Picker

Allows users to select a date.

```
{
  "key": "start_date",
  "name": "Start Date",
  "type": "date",
  "value": "2024-01-01",
  "placeholder": "Select start date"
}
```

**Value Format:** `YYYY-MM-DD`

**Use Cases:**

* Start/end dates
* Expiration dates
* Scheduled dates

***

#### time - Time Picker

Allows users to select time.

```
{
  "key": "backup_time",
  "name": "Backup Time",
  "type": "time",
  "value": "02:00:00",
  "placeholder": "Select backup time"
}
```

**Value Format:** `HH:mm:ss`

**Use Cases:**

* Scheduled task times
* Daily execution times
* Reminder times

***

#### datetime - Datetime Picker

Allows users to select date and time.

```
{
  "key": "schedule_time",
  "name": "Scheduled Execution Time",
  "type": "datetime",
  "value": "2024-01-01 12:00:00",
  "placeholder": "Select execution time"
}
```

**Value Format:** `YYYY-MM-DD HH:mm:ss`

**Use Cases:**

* Scheduled task times
* Event times
* Deadline times

### Auto-Generated Config File

When users modify and save settings in the iClick console, the system will automatically generate a `settings.json` file in the script package directory.

**File Location:**

```
%APPDATA%/iClick/Scripts/com.example.myscript/settings.json
```

**Generated Config File Example:**

```
{
  "api_url": "https://api.example.com",
  "api_key": "your_api_key_here",
  "timeout": 30,
  "enable_log": true,
  "log_level": "info"
}
```

Your external program can directly read this file to get user-configured values.

### Reading Configuration

Your external program can read the auto-generated `settings.json` file to obtain user configuration.

#### Python Example

```
import json
import os

# Read config file
script_dir = os.path.dirname(os.path.abspath(__file__))
settings_file = os.path.join(script_dir, 'settings.json')

with open(settings_file, 'r', encoding='utf-8') as f:
    settings = json.load(f)

# Use configuration
api_url = settings.get('api_url')
api_key = settings.get('api_key')
timeout = settings.get('timeout', 30)
enable_log = settings.get('enable_log', False)

print(f"API URL: {api_url}")
print(f"Timeout: {timeout}s")
```

#### Node.js Example

```
const fs = require('fs');
const path = require('path');

// Read config file
const scriptDir = __dirname;
const settingsFile = path.join(scriptDir, 'settings.json');

const settings = JSON.parse(fs.readFileSync(settingsFile, 'utf-8'));

// Use configuration
const apiUrl = settings.api_url;
const apiKey = settings.api_key;
const timeout = settings.timeout || 30;
const enableLog = settings.enable_log || false;

console.log(`API URL: ${apiUrl}`);
console.log(`Timeout: ${timeout}s`);
```

#### C# Example

```
using System;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Read config file
        string scriptDir = AppDomain.CurrentDomain.BaseDirectory;
        string settingsFile = Path.Combine(scriptDir, "settings.json");
        
        string json = File.ReadAllText(settingsFile);
        var settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
        
        // Use configuration
        string apiUrl = settings["api_url"].ToString();
        string apiKey = settings["api_key"].ToString();
        int timeout = Convert.ToInt32(settings["timeout"]);
        bool enableLog = Convert.ToBoolean(settings["enable_log"]);
        
        Console.WriteLine($"API URL: {apiUrl}");
        Console.WriteLine($"Timeout: {timeout}s");
    }
}
```

### Best Practices

#### 1. Provide Reasonable Default Values

Provide reasonable default values for all configuration items to ensure scripts work properly without modifying configuration.

```
{
  "key": "retry_count",
  "name": "Retry Count",
  "type": "number",
  "value": 3  // Provide default value
}
```

#### 2. Use Meaningful Names

Configuration item `name` should clearly describe the purpose of the configuration.

```
// ✅ Good naming
{
  "key": "api_timeout",
  "name": "API Request Timeout (seconds)",
  "type": "number"
}

// ❌ Poor naming
{
  "key": "timeout",
  "name": "Timeout",
  "type": "number"
}
```

#### 3. Add Placeholder Hints

Add `placeholder` to text input boxes to hint users about what to enter.

```
{
  "key": "webhook_url",
  "name": "Webhook URL",
  "type": "text",
  "placeholder": "e.g., https://hooks.example.com/webhook"
}
```

#### 4. Use Required Fields Appropriately

Only set `require: true` for truly necessary configuration items.

```
{
  "key": "api_key",
  "name": "API Key",
  "type": "text",
  "require": true  // API key is required
}
```

#### 5. Choose Appropriate Configuration Types

Select the most appropriate configuration type based on actual needs:

| Need | Recommended Type |
| - | - |
| Passwords, keys | `text` |
| Toggle options | `checkbox` |
| Fixed options | `select` |
| Long text | `textarea` |
| File paths | `file` or `path` |
| Date/time | `date`, `time`, or `datetime` |

## 5.Complete Examples

This page provides multiple complete script extension examples to help you quickly understand and use the script integration feature.

### Example 1: Device Manager

A comprehensive device management script integrating task execution, UI extensions, and settings panel.

#### manifest.json

```
{
  "id": "com.example.devicemanager",
  "name": "Device Manager",
  "version": "1.0.0",
  "author": "Example Team",
  "description": "External device management panel integration",
  "icon": "icon.png",
  
  "events": {
    "app/run": {
      "action": "$.nodejs.run",
      "args": ["server2.js", "arg1", "arg2"]
    }
  },
  
  "scripts": [
    {
      "id": "open_panel",
      "name": "Open Management Panel",
      "command": {
        "action": "$.shell.open",
        "args": ["DevicePanel.exe", "$.deviceId"]
      }
    },
    {
      "id": "sync_device",
      "name": "Sync Device Info",
      "batch": true,
      "command": {
        "action": "$.http.post",
        "args": [
          "https://api.example.com/sync",
          { "deviceId": "$.deviceId" }
        ]
      }
    }
  ],
  
  "views": {
    "header/slots": [
      {
        "name": "Web Console",
        "icon": "console.png",
        "command": {
          "action": "$.webview.open",
          "args": [
            "https://console.example.com/",
            { "width": 1200, "height": 800 }
          ]
        }
      }
    ]
  },
  
  "settings": [
    {
      "key": "api_url",
      "name": "API Server",
      "type": "text",
      "value": "https://api.example.com",
      "require": true
    },
    {
      "key": "api_key",
      "name": "API Key",
      "type": "text",
      "value": "",
      "placeholder": "Enter your API key",
      "require": true
    },
    {
      "key": "sync_interval",
      "name": "Sync Interval (seconds)",
      "type": "number",
      "value": 60
    },
    {
      "key": "auto_sync",
      "name": "Auto Sync",
      "type": "checkbox",
      "value": true
    }
  ]
}
```

#### Script Structure

```
com.example.devicemanager/
├── manifest.json           # Configuration manifest
├── icon.png                # Script icon
├── console.png             # Console button icon
├── DevicePanel.exe         # External program
└── settings.json           # Auto-generated config file
```

### 6.[Vite Bootstrap](https://github.com/Undefined-Token/iclick-plugin-bootstrap)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.