Skip to content

Utility functions#

General-purpose functions for scripts: logging, waiting, random numbers, hashing and encoding strings, HTTP calls. These functions do not act on the web page.

Log #

Writes one or more values to the log so you can follow how far the script has run. The log shows in Studio (the Logs panel) and in 9Login; in 9Hits campaign macros the function prints nothing, so do not rely on the log as your only way to know the result.

Syntax
Log(msg1, msg2, ...);
Parameters
Name Description
msg1 The value to print, of any type. Objects are printed as JSON; an ArrayBuffer prints only its byte count.
msg2, ... More values to print (optional), separated by tabs on the same line.
Examples
1
2
3
4
5
// print the current URL
Log("Current URL:", await GetUrl());

// objects are printed as JSON
Log({id: 1, ok: true}); // {"id":1,"ok":true}

Delay#

Pauses the script. Pass one number to pause for exactly that many milliseconds; pass two numbers to pause for a random time between ms1 and ms2, which looks more natural.

Syntax
await Delay(ms1, ms2);
Parameters
Name Description
ms1 How long to pause, in milliseconds. When ms2 is given, this is the minimum.
ms2 The maximum, in milliseconds (optional). Ignored if it is not greater than ms1.
Example
await Delay(3000);        // pause 3 seconds
await Delay(3000, 10000); // pause a random 3-10 seconds

Exit#

Ends the session and closes the browser. Use it at the end of a script, or when you want to stop the session early.

Syntax
await Exit();
Example
1
2
3
// if the #start button cannot be clicked, stop the session
const r = await ClickBySelector("#start");
if (r?.error) await Exit();

GetAppVersion#

Returns the version of the app that opened the browser.

Syntax
GetAppVersion();
Returns

The version string, for example "6.0.0".

Example
Log("Version:", GetAppVersion()); // Version: 6.0.0

Random#

The old name of RandomInt; it works exactly the same. New scripts should use RandomInt.

Syntax
Random(value1, value2);
Parameters
Name Description
value1 Called with one number: the upper bound, and the result is from 0 up to but not including value1. Called with two numbers: the lower bound, which can be returned.
value2 The upper bound (optional), never returned. Must be greater than value1.
Returns

An integer.

Example
const n = Random(1, 5); // 1, 2, 3 or 4

RandomInt#

Returns a random integer. Pass one number: the result is from 0 to value1. Pass two numbers: the result is from value1 to value2. The upper bound is never returned.

Syntax
RandomInt(value1, value2);
Parameters
Name Description
value1 Called with one number: the upper bound, and the result is from 0 up to but not including value1. Called with two numbers: the lower bound, which can be returned.
value2 The upper bound (optional), never returned. Must be greater than value1.
Returns

An integer.

Examples
1
2
3
4
5
const a = RandomInt(3);     // 0, 1 or 2
const b = RandomInt(5, 10); // from 5 to 9

// wait a random 0.8-2 seconds
await Delay(RandomInt(800, 2000));

RandomFloat#

Returns a random floating-point number from min to max (not including max). If either parameter is not a number, the function returns a random number from 0 to 1.

Syntax
RandomFloat(min, max);
Parameters
Name Description
min The lower bound, which can be returned.
max The upper bound, never returned.
Returns

A floating-point number.

Example
const ratio = RandomFloat(0.8, 1.2); // e.g. 0.9731...

RandomArray#

Picks a random element from an array, for example one keyword from a ready-made list.

Syntax
RandomArray(array);
Parameters
Name Description
array The array to pick from; its elements can be of any type.
Returns

The picked element, or null when the array is empty or is not an array.

Example
const keyword = RandomArray(["traffic exchange", "auto surf"]);
Log(keyword); // "traffic exchange" or "auto surf"

Md5#

Hashes a string with MD5. Good for keys or checksums; do not use it for passwords or signatures.

Syntax
Md5(input);
Parameters
Name Description
input The string to hash.
Returns

A lowercase hex hash string, 32 characters long.

Examples
1
2
3
4
Log(Md5("abc")); // 900150983cd24fb0d6963f7d28e17f72

// make a key from the current URL
const key = Md5(await GetUrl());

Sha1#

Hashes a string with SHA-1. For anything that needs security, use Sha256.

Syntax
Sha1(input);
Parameters
Name Description
input The string to hash.
Returns

A lowercase hex hash string, 40 characters long.

Example
Log(Sha1("abc")); // a9993e364706816aba3e25717850c26c9cd0d89d

Sha224#

Hashes a string with SHA-224.

Syntax
Sha224(input);
Parameters
Name Description
input The string to hash.
Returns

A lowercase hex hash string, 56 characters long.

Example
Log(Sha224("abc")); // 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7

Sha256#

Hashes a string with SHA-256, the most common choice when you need a hash.

Syntax
Sha256(input);
Parameters
Name Description
input The string to hash.
Returns

A lowercase hex hash string, 64 characters long.

Example
Log(Sha256("abc"));
// ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

Sha384#

Hashes a string with SHA-384.

Syntax
Sha384(input);
Parameters
Name Description
input The string to hash.
Returns

A lowercase hex hash string, 96 characters long.

Example
Log(Sha384("abc")); // "cb00753f45a35e8b..." (96 characters)

Sha512#

Hashes a string with SHA-512.

Syntax
Sha512(input);
Parameters
Name Description
input The string to hash.
Returns

A lowercase hex hash string, 128 characters long.

Example
Log(Sha512("abc")); // "ddaf35a193617aba..." (128 characters)

AesEncryptEx#

Encrypts data with AES (AES-128, AES-192 or AES-256 depending on the key length). Decrypt it with AesDecryptEx using the same key and options.

Syntax
AesEncryptEx(data, key, options);
Parameters
Name Description
data The data to encrypt: a string (read as UTF-8) or an ArrayBuffer.
key A key 16, 24 or 32 bytes long. A string is read as UTF-8; change that with options.keyEncoding.
options.mode Encryption mode: "cbc" (default), "ctr", "ecb", "ofb" or "gcm".
options.iv Initialization vector, required for every mode except "ecb".
options.padding On by default (PKCS7). Pass false or "none" to turn it off.
options.aad Additional authenticated data, only used with "gcm" (optional).
options.tagLength Length of the "gcm" authentication tag, in bytes. Default 16.
options.keyEncoding, options.ivEncoding, options.aadEncoding How key, iv and aad are read when they are strings: "utf8" (default), "hex" or "base64".
options.inputEncoding How data is read when it is a string: "utf8" (default), "hex" or "base64".
options.outputEncoding Output format: "base64" (default), "hex", "utf8" or "buffer" (Uint8Array).
Returns

A base64 string of the encrypted data (or the format chosen in outputEncoding); false when the input is invalid.

Examples
1
2
3
4
5
6
7
8
// AES-256-CBC: 32-byte key, 16-byte iv
const key = "0123456789abcdef0123456789abcdef";
const opts = {mode: "cbc", iv: "abcdef9876543210"};
const enc = AesEncryptEx("hello", key, opts); // "k84ZwsgylwYfVdrcQk0Uww=="

// AES-128-ECB, key written as hex, result as hex
const enc2 = AesEncryptEx("hello", "00112233445566778899aabbccddeeff",
    {mode: "ecb", keyEncoding: "hex", outputEncoding: "hex"}); // "9d86c8612e085e93a235794a708af7a9"

AesDecryptEx#

Decrypts data that was encrypted with AesEncryptEx, using the same key and options.

Syntax
AesDecryptEx(data, key, options);
Parameters
Name Description
data The encrypted data: a base64 string (default) or an ArrayBuffer. For a string in another format, set options.inputEncoding.
key The key used for encryption.
options The same fields as AesEncryptEx. The defaults differ: inputEncoding is "base64" and outputEncoding is "utf8".
Returns

The original string (UTF-8, or the format chosen in outputEncoding); false when the input is invalid or decryption fails, including when "gcm" data fails authentication.

Example
1
2
3
4
const key = "0123456789abcdef0123456789abcdef";
const opts = {mode: "cbc", iv: "abcdef9876543210"};
const text = AesDecryptEx("k84ZwsgylwYfVdrcQk0Uww==", key, opts); // "hello"
if (text === false) Log("Decryption failed");

Base64Encode#

Encodes a string or binary data as Base64. Run objects through JSON.stringify first; otherwise the result is the encoding of the string "[object Object]".

Syntax
Base64Encode(input);
Parameters
Name Description
input A string or an ArrayBuffer. Other types are converted to a string before encoding.
Returns

A Base64 string, or "" when input is empty, null or undefined.

Examples
1
2
3
4
const b64 = Base64Encode("hello 9hits"); // "aGVsbG8gOWhpdHM="

// encode an object
const b64obj = Base64Encode(JSON.stringify({id: 1}));

Base64Decode#

Decodes a Base64 string back to text or binary data.

Syntax
Base64Decode(encodedText, returnAsText=true);
Parameters
Name Description
encodedText The Base64 string to decode.
returnAsText true (default) returns a UTF-8 string; use it only for text. For images or binary files, pass false to get an ArrayBuffer, otherwise the data gets corrupted.
Returns

A string when returnAsText is true, otherwise an ArrayBuffer.

Examples
1
2
3
4
5
const text = Base64Decode("aGVsbG8="); // "hello"

// a page screenshot as binary data
const bytes = Base64Decode(await CapturePage(), false);
Log(bytes); // ArrayBuffer (byte count of the image)

HttpRequest#

Sends an HTTP request from the script, for example to call an external API or to fetch data for a macro. The request does not carry the page's cookies. Note: by default the request goes directly from the computer, not through the session's proxy (see bypassProxy).

Syntax
await HttpRequest(url, data, timeout=0, headers=null, returnAsBuffer=false, bypassProxy=true);
Parameters
Name Description
url The full address, for example "https://httpbin.org/get".
data Empty or null to send a GET. With a value, it sends a POST: a string is sent as JSON (application/json), an object as a form, an ArrayBuffer as binary.
timeout Maximum wait time, in milliseconds. 0 (default) waits at most 30 seconds.
headers An object of headers to send, for example {"Authorization": "Bearer abc"}. Set Content-Type here to replace the type that the function picks from data. Default null.
returnAsBuffer true to get body as an ArrayBuffer (images, files). Default false: body is a string.
bypassProxy true (default): the request does not go through the session's proxy, so the server sees the computer's real IP. Pass false to go through the session's proxy.
Returns

Object {status, headers, body}: status is the HTTP code, headers is a {name: value} object and body is the response content. On a network error or timeout: {status: 0, error}, with the reason in error.

Examples
// GET
const r = await HttpRequest("https://httpbin.org/get");
Log(r.status, r.body); // 200 {"args": {}, ...}

// POST as a form
const r2 = await HttpRequest("https://httpbin.org/post", {p1: 1, p2: 2});

// POST JSON through the session's proxy, waiting at most 15 seconds
const r3 = await HttpRequest("https://httpbin.org/post", JSON.stringify({p1: 1}), 15000, null, false, false);
if (r3.status === 0) Log("Error:", r3.error);

// GET with a header
const r4 = await HttpRequest("https://api.example.com/me", null, 0, {"Authorization": "Bearer abc"});

GenerateXpath#

Builds an xpath string from a tag name, an attribute and a value, for use with functions that take an xpath, such as ClickByXpath.

Syntax
GenerateXpath(tag, attr, value, index);
Parameters
Name Description
tag Tag name, for example "a", "div", "button".
attr Attribute name, for example "href", "class". Use "text" to match the text inside the element.
value The value to match. Wrap it in % to choose how it matches: "%x%" means contains, "x%" means starts with, "%x" means ends with, and no % means exactly equal.
index A position number appended to the end of the xpath as [index], counting from 1 as xpath does (optional). Empty or 0 appends nothing.
Returns

An xpath string, or "" when tag, attr or value is missing or one of the three is not a string.

Examples
// a link whose href is exactly "http://google.com"
GenerateXpath("a", "href", "http://google.com"); // '//a[@href="http://google.com"]'

// a link whose href starts with "http://google"
GenerateXpath("a", "href", "http://google%"); // '//a[starts-with(@href, "http://google")]'

// a link whose href ends with "google.com"
GenerateXpath("a", "href", "%google.com");

// a div whose class contains "product"
GenerateXpath("div", "class", "%product%"); // '//div[contains(@class, "product")]'

// click the button with the text "Sign in"
await ClickByXpath(GenerateXpath("button", "text", "Sign in"));

GetProfileInfo #

Tells you which 9Login profile the script is running in: the profile's ID, its name and its position in the profile table when it was opened.

Syntax
GetProfileInfo();
Returns

Object {id, title, index}, or null in 9Hits campaign macros. id is the profile ID, title is the profile name, and index is the position counted from 0 in the table order when the profile was opened (row 1 has index 0). To recognize a profile across several runs, use id.

Example
const p = GetProfileInfo();
if (p) Log(`#${p.index + 1} ${p.title} (${p.id})`); // #1 Profile A (...)

A function for 9Login

In 9Hits campaign macros the function returns null. When you test-run in Studio, it returns placeholder values (id is "macro-test", title is "Studio", index is 0). Use this function in 9Login scripts.