Snippet Code
The collection of useful snippet code for the Scripting tool

1. What's it?

A collection of snippet Javascript code for the Scripting Tool.
Could not find the Snippet Code you are looking for?
Please open a ticket at https://github.com/ProxymanApp/Proxyman, we will get back to help you ⭐️

2. Common on Request and Response

3. Addons

4. Regex

5. Import / Export Files

6. Miscellaneous

7. Encryption/Decryption

8. Map Remote with Scripting

HTTP Header

Add/Update: Request or Response Header

1
function onRequest(context, url, request) {
2
// Add or update Request Header
3
request.headers["X-Proxyman-Key"] = "My-Value";
4
request.headers.name = "Proxyman";
5
return request;
6
}
7
8
function onResponse(context, url, request, response) {
9
// Add or update Response Header
10
response.headers["X-Proxyman-Key"] = "My-Value";
11
response.headers.id = 100;
12
return response;
13
}
Copied!

Delete: Request or Response Header

1
function onRequest(context, url, request) {
2
delete request.headers["X-Proxyman-Key"];
3
return request;
4
}
5
6
function onResponse(context, url, request, response) {
7
delete response.headers["X-Proxyman-Key"];
8
return response;
9
}
10
Copied!

Request Query

Add/Update

1
function onRequest(context, url, request) {
2
request.queries["name"] = "Proxyman";
3
request.queries["platform"] = "macOS";
4
// => http://proxyman.io?name=Proxyman&platform=macOS
5
return request;
6
}
Copied!

Delete

1
function onRequest(context, url, request) {
2
delete request.queries["name"];
3
delete request.queries["platform"];
4
return request;
5
}
6
Copied!

URLEncoded Form Body

Add/Update

1
function onRequest(context, url, request) {
2
// Make sure the Response Header is application/x-www-form-urlencoded
3
// Content-Type: application/x-www-form-urlencoded
4
var formBody = request.body;
5
6
formBody["name"] = "Proxyman";
7
formBody["flatform"] = "macOS";
8
9
request.body = formBody; // => name=Proxyman&platform=macOS
10
return request;
11
}
12
Copied!

Delete

1
function onRequest(context, url, request) {
2
// Content-Type: application/x-www-form-urlencoded
3
var formBody = request.body;
4
5
delete formBody["name"];
6
delete formBody["flatform"];
7
8
request.body = formBody;
9
return request;
10
}
11
Copied!

Change Request Destination (scheme, host, port, path)

1
function onRequest(context, url, request) {
2
request.scheme = "http";
3
request.host = "proxyman.dev";
4
request.port = 9090;
5
request.path = "v1/data/user";
6
return request;
7
}
Copied!

Change HTTP Request Method

1
function onRequest(context, url, request) {
2
request.method = "POST";
3
return request;
4
}
Copied!

Change Response HTTP Status Code

1
function onResponse(context, url, request, response) {
2
response.statusCode = 404;
3
return response;
4
}
Copied!

JSON Body

On Request

1
function onRequest(context, url, request) {
2
// Set JSON content
3
request.headers["Content-Type"] = "application/json";
4
5
// Get Request body
6
var jsonBody = request.body;
7
8
// Modify data
9
jsonBody["name"] = "Proxyman";
10
jsonBody["flatform"] = "macOS";
11
jsonBody["info"] = {
12
"website": "proxyman.io",
13
"region": "Earth"
14
};
15
// Set it again
16
request.body = jsonBody;
17
return request;
18
}
Copied!

On Response

1
function onResponse(context, url, request, response) {
2
// Set JSON content
3
response.headers["Content-Type"] = "application/json";
4
5
// Get Request body
6
var jsonBody = response.body;
7
8
// Modify data
9
jsonBody["name"] = "Proxyman";
10
jsonBody["flatform"] = "macOS";
11
jsonBody["info"] = {
12
"website": "proxyman.io",
13
"region": "Earth"
14
};
15
// Set it again
16
response.body = jsonBody;
17
return response;
18
}
19
Copied!

Map a local file to Response's Body like Map Local Tool (Proxyman 2.25.0+)

It's a convenient way to directly set a local file to a Body by using bodyFilePath property
1
// For request
2
request.bodyFilePath = "~/Desktop/image.png";
3
4
// For response
5
response.bodyFilePath = "~/Desktop/image.png";
Copied!
1
function onResponse(context, url, request, response) {
2
3
response.headers["Content-Type"] = "image/png";
4
response.bodyFilePath = "~/Desktop/image.png";
5
6
// Done
7
return response;
8
}
Copied!
1
function onResponse(context, url, request, response) {
2
3
response.headers["Content-Type"] = "application/json";
4
response.bodyFilePath = "~/Desktop/my_response.json";
5
6
// Done
7
return response;
8
}
Copied!

Use JSON File as a Body of Request or Response

It's possible to use your JSON file and set it as a Request/Response's body
Please follow this tutorial.

Use multiple JSON files

You can use set a different body for each matching endpoint by using the IF statement.
    1.
    Follow this tutorial to understand how to import a JSON file to the script
    2.
    Set Script Rule with wildcard or Regex pattern that can match many endpoints. E.g https://my-domain.com/v*
    3.
    Use `includes()` to check whether or not the endpoint is matched
1
const file_1 = require("@users/myfile_1.json");
2
const file_2 = require("@users/myfile_2.json");
3
const file_3 = require("@users/myfile_3.json");
4
5
function onResponse(context, url, request, response) {
6
7
// Set JSON content
8
response.headers["Content-Type"] = "application/json";
9
10
// Check
11
if (url.includes("v1/data")) {
12
response.body = file_1
13
} else if (url.includes("v2/login")) {
14
response.body = file_2
15
} else if (url.includes("v3/user")) {
16
response.body = file_3
17
}
18
19
// Done
20
return response;
21
}
Copied!

Map Local with GraphQL

1
// Import your JSON file here
2
const file = require("@users/B02D96D5.default_message_32E64A5B.json");
3
4
function onRequest(context, url, request) {
5
6
// 1. Extract the queryName from the request
7
var queryName = request.body.query.match(/\S+/gi)[1].split('(').shift();
8
9
// 2. Save to sharedState
10
sharedState.queryName = queryName
11
12
// Done
13
return request;
14
}
15
16
function onResponse(context, url, request, response) {
17
18
// 3. Check if it's the request we need to map
19
if (sharedState.queryName == "user") {
20
21
// 4. Import the local file by Action Button -> Import
22
// Get the local JSON file and set it as a body (like Map Local)
23
response.headers["Content-Type"] = "application/json";
24
response.body = file;
25
}
26
27
// Done
28
return response;
29
}
Copied!

Use ArrayBuffer in Request/Response Body

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 and set the ContentType to application/octet-stream
Proxyman will convert Base64 Encoding to ArrayBuffer, so the client will receive the data properly.
1
// Import
2
const { btoa } = require('@addons/Base64.js');
3
4
function onResponse(context, url, request, response) {
5
// Construct the ArrayBuffer
6
const buffer = new ArrayBuffer(256)
7
const view = new Uint8Array(buffer)
8
for (let i = 0; i < view.length; i++) {
9
view[i] = i
10
}
11
12
// Convert ArrayBuffer to Base64String
13
var newBody = btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
14
15
// Set new body
16
response.body = newBody;
17
response.statusCode = 200
18
response.headers['Content-Type'] = 'application/octet-stream'
19
20
// Done
21
return response;
22
}
Copied!

Preserve the Host

1
function onRequest(context, url, request) {
2
request.preserveHostHeader = true
3
return request
4
}
Copied!

Comment & Highlight with color

Use comment or color to highlight on the main table view.
1
function onRequest(context, url, request) {
2
request.comment = "It's a Request"
3
request.color = "red" // red, blue, yellow, purple, gray, green
4
return request
5
}
6
7
function onResponse(context, url, request, response) {
8
response.comment = "It's a Response"
9
response.color = "yellow" // red, blue, yellow, purple, gray, green
10
return response
11
}
Copied!
Use Scripting for Color and Comment

Import Files with require()

JSON

    1.
    Prepare a JSON file and save it to your Desktop
1
// myfile.json
2
{
3
"name": "Proxyman",
4
"platform": "macOS",
5
"info": {
6
"website": "proxyman.io",
7
"region": "Earth"
8
}
9
}
Copied!
2. More -> Import JSON or Other Files. Then selecting your file
3. Proxyman will add the import code to the top of the script
1
// ~/Library/Application Support/com.proxyman.NSProxy/users/myfile.json
2
const file = require("@users/myfile.json");
3
4
function onResponse(context, url, request, response) {
5
// 1. Set header to JSON if need
6
response.headers["Content-Type"] = "application/json";
7
8
// 2. Set Body as a imported file
9
response.body = file;
10
11
return response;
12
}
Copied!
The selected file is copied to ~/Library/Application\ Support/com.proxyman.NSProxy/users folder.
To support other format files, such as image, text, pdf. Make sure you have correct Header Content-Type

Binary File

    1.
    Follow the same above instruction (Select your Binary File)
    2.
    Set it as a body
1
// ~/Library/Application Support/com.proxyman.NSProxy/users/myscreenshot.png
2
const file = require("@users/myscreenshot.png");
3
4
function onResponse(context, url, request, response) {
5
// Set header
6
response.headers["Content-Type"] = "image/png";
7
8
// Set Body
9
response.body = file;
10
11
return response;
12
}
Copied!

Text-Based File

    1.
    Follow the same above instruction (Select your Binary File)
    2.
    Set it as a body
1
// ~/Library/Application Support/com.proxyman.NSProxy/users/main.css
2
const file = require("@users/main.css");
3
4
function onResponse(context, url, request, response) {
5
// Set header
6
response.headers["Content-Type"] = "text/css";
7
8
// Set Body
9
response.body = file;
10
11
return response;
12
}
Copied!

Import File without using the "Import Tool"

From Proxyman 2.24.0+, you can import any files without using the "Import File".
1
// Import your file from your Desktop folder
2
const file = require("~/Desktop/myfile.json");
3
4
function onResponse(context, url, request, response) {
5
6
// 1. Set header to JSON if need
7
response.headers["Content-Type"] = "application/json";
8
9
// 2. Set Body as a imported file
10
response.body = file;
11
12
return response;
13
}
Copied!
    If the file has ".js" as an extension => Proxyman will execute it as a JS Script
    Otherwise, Proxyman will import it as normal
Only files that are imported by using the "Import Tool", are included when exporting the script to your colleague.

Use as Mock API

You can use Scripting as a Mock API by following this guideline.

Using Addons

Use Base64 Addon

1
// Encode Base64
2
const { btoa } = require("@addons/Base64.js")
3
4
// Usage:
5
var text = "HelloWorld";
6
var encodedText = btoa(text);
Copied!
1
// Decode Base64
2
const { atob } = require("@addons/Base64.js")
3
4
// Usage:
5
var text = atob("aGVsbG8=");
Copied!

Use Hashing Addon (MD5, SHA1, SHA256, SHA512)

1
// Hash MD5
2
const { md5 } = require("@addons/MD5.js")
3
4
// Usage:
5
var hashedText = md5("Hello World");
Copied!
1
// Hash SHA1
2
const { sha1 } = require("@addons/SHA1.js")
3
4
// Usage:
5
var hashedText = sha1("Hello World");
Copied!

Use UUID-v4 Addon

1
// Hash MD5
2
const { uuidv4 } = require("@addons/UUID.js")
3
4
// Usage:
5
var uuid = uuidv4();
Copied!

Deflate/Inflate and GZip/UnGZip

Deflate/inflate

1
const { inflate, deflate } = require("@addons/Pako.js")
2
3
// Compress
4
var input = "Hello World from Pako!!!"
5
var result = deflate(input);
6
console.log(result); // eJzzSM3JyVcIzy/KSVFIK8rPVQhIzM5XVFQEAGsMB/8=
7
8
// Decompress
9
var text = 'eJzzSM3JyVcIzy/KSVFIK8rPVQhIzM5XVFQEAGsMB/8=';
10
var rawText = inflate(text);
11
console.log(rawText); // Hello World from Pako!!!
Copied!

GZip/UnGZip

1
const { ungzip, gzip } = require("@addons/Pako.js")
2
3
// Compress
4
var text = 'HelloWorld';
5
var result = gzip(text);
6
console.log(result); // H4sIAAAAAAAAA/NIzcnJD88vykkBAHkMd3cKAAAA
7
8
// Decompress
9
var text = 'H4sIAAAAAAAAA/NIzcnJD88vykkBAHkMd3cKAAAA';
10
var rawText = ungzip(text);
11
console.log(rawText); // HelloWorld
Copied!

JWT Decode

1
const { jwtDecode } = require('@addons/JWTDecode.js');
2
3
var text = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
4
var jSONObject = jwtDecode(text)
Copied!

Logging

1
// Print the obj
2
const myObj = {};
3
console.log(myObj);
4
5
// Print type of the obj
6
console.log(typeof(myObj));
Copied!

Regex

Only number

1
//Init Regex
2
var reg = /^-?\d*\.?\d*$/;
3
4
if (reg.test("123123123")) {
5
console.log("Matched");
6
}
Copied!

Miscellaneous

By-pass CORS

1
function onResponse(context, url, request, response) {
2
3
// Allow all
4
response.headers["Access-Control-Allow-Origin"] = "*";
5
6
// Done
7
return response;
8
}
Copied!

Inject Header to Request / Response

1
function onRequest(context, url, request) {
2
// add header
3
request.headers["My-Injected-Header"] = "Proxyman";
4
return request
5
}
6
7
function onResponse(context, url, request, response) {
8
// add header
9
response.headers["My-Injected-Header"] = "Proxyman";
10
return response;
11
}
12
Copied!

Response delay with sleep() function

1
function onResponse(context, url, request, response) {
2
console.log("Start sleep");
3
4
// Sleep 5 seconds
5
sleep(5000);
6
7
// Done
8
return response;
9
}
Copied!

AES Encryption/Decryption

1
const { encryptAES, decryptAES } = require("@addons/CryptoJS.js")
2
3
function onRequest(context, url, request) {
4
5
// Encrypt
6
var message = 'my message from Proxyman';
7
var password = 'secret key 123';
8
var ciphertext = encryptAES(message, password);
9
10
// Decrypt
11
var originalText = decryptAES(ciphertext, password);
12
13
// Done
14
return request;
15
}
Copied!

DES Encryption/Decryption

1
const { encryptDES, decryptDES } = require("@addons/CryptoJS.js")
2
3
function onRequest(context, url, request) {
4
5
// Encrypt
6
var message = 'my message from Proxyman';
7
var password = 'secret key 123'