Scripting

1. What's it?

Proxyman offers a scripting feature that the developer could write the JS code to manipulate the Request/Response in a flexible way.

2. Benefits

  • Implement Map Local / Map Remote / Breakpoint by JS Code. 100x Faster

  • Change the Request Content, includes Domain, Host, Scheme, Port, Path, HTTP Method, HTTP Headers, Query, Body (Encoded-Form, JSON, plain-text)

  • Change the Response Content, includes HTTP Status Code, HTTP Headers, Body (JSON, Encoded-Form, plain-text, binary...)

  • Provide plenty of built-in addons and libraries for common tasks, such as Hashing, Encode/Decode, JSON-Text transformer, Beautify,...

  • Able to write your own JS Addons or Libraries

  • Designed to replace Rewrite GUI Tool

  • Assign and receive shared States between each script or current session with ShareState or Environment Variables

3. How to use it?

You can access the Scripting Tool by:

  • Script Menu -> Script List (⌥⌘I)

  • Open Menu Context from Right Click on the Flow -> Tools -> Scripting

Checkout Snippet Code to see a collection of snippet JS code for the Scripting Tool.

4. Examples

The following guide will show you how to write JS code to change the Request domain from Production to Localhost and change the Response Body

  1. Make sure you enable SSL for this domain before creating the script)

  2. Open Scripting Tool and create new Script Entry (⌘N). You can right-click on the Request -> Tools -> Scripting => Proxyman will create a Script too

  3. Give the name and define a Matching Rule.

  4. Ex: Name=Test on Localhost endpoint, URL=https://proxyman.io

  5. Enable Run Script on Request and Response checkbox

  6. Start writing JS code for onRequest function

onRequest(context, url, request) {}

// Import UUID addons
const { uuidv4 } = require("@addons/UUID.js");
///
/// This func is called if the Request Checkbox is Enabled
/// You can manipulate the Request Data here before the request hits on the server
/// Ex: Add/Update/Remove HTTP Header, Query, Form, Body, Host, Port, Path
/// Use console.log(request) to see all available fields
///
function onRequest(context, url, request) {
// print log
console.log(request);
// Change Production domain -> Localhost
request.method = "GET";
request.schema = "http";
request.host = "localhost";
request.port = 8000;
// Add new header
request.headers["X-New-Header"] = "Hello From Scripting feature";
request.headers["UUID"] = uuidv4(); // generate random UUIDv4
delete request.headers["Key-Need-Delete"];
// Update or Add a new Query
request.queries["name"] = "Proxyman";
// Done
return request;
}

onRequest() Object Format

context, url and request objects are defined by:

// context (readonly)
{
"scriptName": "<String> Your Script Name",
"matchingRule": "<String> Your Matching Rule",
"matchingMethod": "<String> Method",
"isEnableOnRequest": "Bool",
"isEnableOnResponse": "Bool",
"filePath": "<String> Script path"
}
// url (readonly)
url: String // => Present the full URL
// request
{
"method": "<String> HTTP Method. Accept string method. Ex: GET, POST, ...",
"schema": "<String> Accept http or https",
"host": "<String> Host of the request. Ex: api.proxyman.io, localhost, ...",
"path": "<String>: Path of the URL. Ex: /v1/data",
"port": "<Int> Accept int port number. Ex: 443, 8080, ..",
"queries": "<[String: Any]> A JS Object (Dictionary) contains key values of the query",
"headers": "<[String: Any]> A JS Object (Dictionary) contains key values of the header",
"body": "Depend on the Content-Type header. It might be a dictionary for JSON and form, Plain Text or Base64 Encoded String",
"rawBody": "<Readonly>: A raw body String or Base64 encoded string if it's a binary"
}

You can change any value of the request obj except rawBody

If the body variable is invalid format due to incorrect Content-Type in the Header. Please consider to use rawBody and manually parse the string.

The type of request.body replies on the Content-Type Header.

Content-Type Header

request.body

application/json or JSON families

Javascript Object

application/x-www-form-urlencoded

Javascript Object

plain-text or text-based Content-Type, Ex: application/js, text/css, text/html, ...

String

The rest (application/zip, application/octet-stream)

Base64 Encoded String

Check out common JS code from Snipped Code Page

7. Start writing code on onResponse function

///
/// This func is called if the Response Checkbox is Enabled
/// You can manipulate the Response Data here before it goes to the client
/// Ex: Add/Update/Remove HTTP Header, Status, Body,...
/// Use console.log(response) to see all available fields
///
function onResponse(context, url, request, response) {
console.log(response);
// Update or Add a new header
response.headers["Content-Type"] = "application/json";
// Update status Code
response.statusCode = 500;
// Update Body
var body = response.body;
body["new-key"] = "Proxyman";
response.body = body;
// Done
return response;
}

onResponse() Objects Format

context, url, request, and response objects are defined by:

// context (readonly): Same with onRequest
// url (readonly): Same with onRequest
// request (readonly): Same with onRequest
// response
{
"statusCode": "<Int> Status Code. Ex: 200, 400, 404,...",
"httpVersion": "<String><Readonly> The HTTP Version",
"statusPhrase": "<String><Readonly> HTTP Status Phrase. Ex Not Found, OK, ...",
"headers": "<[String: Any]> A JS Object (Dictionary) contains key values of the header",
"body": "Depend on the Content-Type header. It might be a dictionary for JSON and form, PlainText or Base64 Encoded String"
}

You can change statusCode, headers and body from the response Obj

If the body variable is invalid format due to incorrect Content-Type in the Header. Please consider to use rawBody and manually parse the string.

The type of response.body replies on the Content-Type Header

Content-Type Header

request.body

application/json or JSON families

Javascript Object

application/x-www-form-urlencoded

Javascript Object

plain-text or text-based Content-Type, Ex: application/js, text/css, text/html, ...

String

The rest (application/zip, application/octet-stream)

Base64 Encoded String

You must return request and response object in onRequest and onResponse function

3. Built-in Addons and Libraries

Proxyman provides plenty of addons and libraries that help you achieve common tasks: Hashing, Encode/Decode, ...

4. Debugging JS Error

On certain occasions, you might encounter Javascript error due to syntax error, invalid code, ... You can debug by looking the error message on the console or using console.log()

5. Notes

  • You must return request and response Object in onRequest and onResponse function

  • Since Javascript doesn't have the Data object type, the Data Body will convert to Base64 Encoded String in Javascript

  • To pass Uint8Array, blob, or ArrayBuffer to the body, make sure you convert to Base64 Encoded String

// Your binary, Uint8Array, blob data,...
var myData = fromFile();
// Import
const { btoa } = require('@addons/Base64.js');
// Convert to base64 encoded string
response.body = btoa(myData);