ScriptBuilder Execute Code Instruction
  • 1 Minute to read
  • Dark
    Light
  • PDF

ScriptBuilder Execute Code Instruction

  • Dark
    Light
  • PDF

Article Summary

The Execute code instruction can run a Javascript code during the automated test run.

You can use the Execute code instruction to -

  • Run generic JavaScript code functions, such as API calls

  • Access or modify the browser DOM and display alerts with Web API functions such as document.getElementById, alert, and others.

You can use the following shortcuts in your JavaScript code - httpGet, httpPost, and PanayaVars.

httpGet

Our httpGet shortcut for HTTP GET requires a URL and returns a string.

Examples -

var productJson = httpGet('https://.com/products/1');
Response - product = '{"id":1,"title":"Short Cables","description":"Short cables that will hold forever","price":549}’.
var product = JSON.parse(productJson); panayaVars.productPrice = product.price; // if the response is a Javascript object
var product = parseFloat(productJson); // if the response is a string and not an Javascript object like: '549'

Good to know!

If you need to extract a Javascript object from the response, use - JSON.parse(response).

httpPost

Our httpPost shortcut for HTTP POST requires the following two parameters and returns a string. -

  • URL of the page that contains the data

  • Data sent as application/x-www-form-urlencoded (the keys and values are encoded in key-value tuples separated by ‘&', with a ‘=' between the key and the value. Non-alphanumeric characters in both keys and values should be URL encoded) E.g.: id=123&category=book

Good to know!

If you need to extract a Javascript object from the response, use - JSON.parse(response).

Examples -

var book = httpPost(’https://products.com’, 'id=123&category=Books');

Response example: book = ‘{ “id”: 123, “name”: “Alice in Wonderland”, “price”: 45.85 }’.

Parsing & extraction data example

var bookPrice = JSON.parse(book).price; // if we need only one property from the response object

var bookObj = JSON.parse(book); var bookPrice = bookObj.price; var bookName = bookObj.name + ' - Our super offer'; // if multiple properties are needed from the response object


PanayaVars

The script can access Panaya Variables (Read or Write) using the following syntax -
panayaVars.parameterName.

In the example above, the parameterName is the name of the parameter defined in the script using the Set parameter instruction. When the script execution is complete, Panaya variables are sent back to the ScriptBuilder / Agent application with their current value.

Use the syntax below to read a Panaya variable -

JSON.parse(response)

var scriptPrice = panayaVars.price * 5;
The price is the parameter defined in the application.

Use the syntax below to write a Panaya variable -

panayaVars.price = 100.25;

The price is the parameter defined in the application.