脚本(Script)
Loon 3.5.1 (983) 起支持的新版 Script 语法统一了 Request、Response、Cron、Network Changed 和 Generic Script 的配置格式,并为 HTTP Script 增加了多条件匹配。
脚本内可用的 JavaScript 对象和方法没有改变,参见 Script API。
适用来源
主配置 [Script]、[Remote Script] 和插件 [Script] 使用相同的语法、默认值与校验规则。插件 Script 还可以引用当前插件的 [Argument] 参数。
可视化工具
可以使用 Script 配置编辑器 生成新语法,或使用 Script 语法转换器 迁移旧版配置。
快速开始
所有类型都使用统一的 script(...) Action:
HTTP <request|response> if <condition> then script(<path> [, <argument>]) [with <options>]
Cron cron <cron-expression> then script(<path> [, <argument>]) [with <options>]
Network Changed network-changed then script(<path> [, <argument>]) [with <options>]
Generic generic then script(<path> [, <argument>]) [with <options>]
一个完整的 HTTP 示例:
request if ${url} ~= /^https:\/\/api\.example\.com/i && ${request.method} == "POST" then script("request.js", "source=profile") with tag="Request Script", timeout=20, requires_body=true
每条配置由三部分组成:
| 部分 | 作用 | 示例 |
|---|---|---|
| Trigger / Condition | 决定何时触发或是否命中 | request if ...、cron "..." |
| Script Action | 指定脚本路径和 $argument | script("request.js", "debug=true") |
with | 设置该条指令的属性 | with tag="Request", timeout=20 |
Script 类型
Request Script
在请求发出前匹配并执行:
request if ${url} ~= /\/api\// && ${request.method} == "POST" then script("request.js") with requires_body=true
- 省略
requires_body或设为false时,在 Request Header 阶段执行。 requires_body=true时,等待完整 Request Body 后执行。- 同一请求最多选择一条 Request Script,按最终配置顺序使用第一条完整命中的规则。
Response Script
根据请求和原始响应信息匹配:
response if ${url} ~= /\/api\// && ${response.status} == 200 && ${response.header['Content-Type']} ~= /application\/json/i then script("response.js") with requires_body=true
- 每条 Response Script 必须包含强制 URL Guard,详见 Response URL Guard。
- 省略
requires_body或设为false时,在 Response Header 阶段执行。 requires_body=true时,等待完整 Response Body 后执行。- 同一响应最多选择一条 Response Script,并保持原配置顺序。
Cron Script
按 Cron 表达式定时执行:
cron "0 8 * * *" then script("cron.js") with tag="Daily Task", timeout=300
支持五段或六段格式:
* * * * * 分 时 日 月 周
* * * * * * 秒 分 时 日 月 周
插件可以使用 String 类型参数提供动态 Cron:
cron ${cron} then script("cron.js", {${region}}) with enable=${enabled}, tag="Plugin Cron"