Skip to Content
JavsScript 脚本语法与接口

语法与接口

基础方法

  • $script.name:脚本名称
  • $script.type:脚本类型,如 request, response 和 tile
  • $script.startTime:脚本开始运行的时间
  • $environment["stash-build"]:Stash Build 编号
  • $environment["stash-version"]:Stash 版本号
  • $environment.language:Stash 运行语言
  • $environment.system:Stash 运行系统 (iOS / macOS)
  • $argument:运行参数。仅在配置了 argument 时存在。
  • $done(value):结束脚本运行,释放资源
  • $notification.post(title, subtitle, body):发送系统通知
  • console.log(value):输出日志,脚本日志会输出到单独的文件。传入对象时会自动序列化为 JSON。
  • setTimeout(callback, delay):延迟执行回调函数

脚本抛出未捕获的异常时,本次运行会立即终止,异常信息会记录到脚本日志中。

定时器

iOS/tvOS3.6+macOS4.3+

除 setTimeout 外,脚本还可以使用 setInterval、clearTimeout 和 clearInterval,以及 queueMicrotask。脚本运行结束时,尚未触发的定时器会一并取消。

$done(value)

⚠️

对于所有脚本,在结束时候必须调用 $done(value) 方法释放资源。

$done 只有第一次调用生效。在脚本编辑器中运行脚本时,传给 $done 的值会显示在编辑器中,便于调试。

持久化存储

  • $persistentStore.write(value, key):写入持久化存储。value 必须是字符串,写入成功返回 true。
  • $persistentStore.read(key):读取持久化存储,不存在时返回 null。

省略 key 时,以脚本名称作为键,因此同一个脚本在不同场景(HTTP 改写、定时任务、面板)下共享同一份数据;需要在多个脚本之间共享数据时,显式指定相同的 key。

HTTP Client

  • $httpClient.get(url<String>, callback<Function>)
  • $httpClient.get(request<Object>, callback<Function>)

同样地,还有:

  • $httpClient.post()
  • $httpClient.put()
  • $httpClient.delete()
  • $httpClient.head()
  • $httpClient.options()
  • $httpClient.patch()

request 对象支持以下字段:

字段类型说明
urlstring必填,请求地址
headersobject请求头。设置 X-Stash-Selected-Proxy 可指定请求使用的代理,值需要经过 encodeURIComponent 编码
bodystring / object / Uint8Array / ArrayBuffer请求体。传入对象时自动序列化为 JSON 字符串
timeoutnumber超时时间,单位为秒,默认为 5
insecureboolean设为 true 时不校验 HTTPS 证书,默认为 false
binary-modeboolean设为 true 时,响应 data 以 Uint8Array 返回,默认为 false
auto-cookieboolean自动处理 Cookie,默认为 true
auto-redirectboolean自动跟随 3xx 重定向,默认为 true

回调函数的签名为 callback(error, response, data):请求失败时 error 为错误信息字符串;成功时 response 包含 status(亦可通过 statusCode 读取)和 headers,data 为响应体。headers 对象的键名不区分大小写。

例如:

$httpClient.get('http://httpbin.org/get', (error, response, data) => { if (error) { console.log(error) } else { console.log(data) } }) const yourProxyName = 'a fancy name with 😄' $httpClient.post( { url: 'http://httpbin.org/post', headers: { 'X-Header-Key': 'headerValue', 'X-Stash-Selected-Proxy': encodeURIComponent(yourProxyName), }, body: '{}', // can be object or string timeout: 5, insecure: false, 'binary-mode': true, 'auto-cookie': true, 'auto-redirect': true, }, (error, response, data) => { if (error) { console.log(error) } else { console.log(data) } } )
Last updated on