Available from Surge Mac 3.2.0 / Surge iOS 3.8
[Script] http-response .* script-path=script.js
Each line includes three parts:
- Script type. Only 'http-response' is supported now.
- A regular expression for URL. The script will only apply to the matched requests.
- Parameters, separated by commas
- script-path: The path of the script file. You may use a relative path (in the same directory of the profile), an absolute path or a URL here.
- script-update-interval: If you are using a URL in script-path, you may specify the automatic update interval. Default value: 86400s.
- max-size: The maximum size of the response body, which the script is allowed to modify. Default value: 131072 (128KB).
Scripting requires Surge to load the entire response body data to memory. A huge response body may cause Surge iOS crash since the iOS system limits the maximum amount of memory which the Network Extension can occupy. (20MB at most in iOS 12)
Please only enable scripting for necessary URLs.
If the response body size exceeds 'max-size' value, Surge fallbacks to passthrough mode and skip scripting for this request.
Write a script
Surge will pass several global variables to JS context:
- body[String]: HTTP response body
- status[Number]: HTTP status code
- method[String]: HTTP method
- headers[Object]: HTTP response headers
- url[String]: Full URL address
Surge uses the last value generated by the script as a result. Here is the definition of the type of result:
- String: Use it as the new response body.
- Null: Abort the request.
- undefined: Do not touch the response.
- Object: complex modification
- If 'body' property exists, use it as the new response body.
- If 'headers' property exists, use them as the new response headers. Please notice that 'Content-Length', 'Transfer-Encoding' and 'Content-Encoding' can't be overwritten.
- If 'status' property exists, use it as the new HTTP status code.
An easy example:
var obj = JSON.parse(body); obj['surge'] = 'OK'; JSON.stringify(obj);
- By default, a new JS context will be created for each scripting executing. You may configure 'shared-jsvm-context' to let all scripts share a JS context, which allows scripts to share data with global variables.
- You may use 'console.log' to log to Surge's log file.
- The response header and body in Surge Dashboard are modified versions. You may inspect the script executing status in Notes Tab.