Guides

JavaScript Functions in miniApps

Overview

JS functions in miniApps® are strings that represent a JS expression or a sequence of JS statements that are evaluated and executed. The return value is the value of the last executed expression, and its type is specified by the type of the function.

miniApps® JS functions are like separate, totally independent scripts. You can not invoke a JS function from within another.

JS functions can be found in the following miniApps® areas:

Isolated mode is now mandatory (2.40.1)
Every JS function (User, Validation, Output) must return its result using ocpReturn(...).
Legacy mode (ending a script with a bare trailing expression, with no ocpReturn) is deprecated.
From this release, saving or updating a miniApp is rejected if any JS snippet does not call ocpReturn. Existing miniApps should be migrated to ocpReturn at the next edit.

Practical guidance
If a save fails with a legacy-mode error, locate the snippet that ends in a bare expression and wrap the returned value in ocpReturn(...).

Types of JS functions

User functions

User functions help do computations and provide an outcome that can be announced or used later as input to another miniApp, and replace an endpoint or a request body in WebService miniApps.
You can use Javascript, write your own code, apply your business logic and at the end literally return a string.

Your javascript function must always return a string in the end.

Example:

A user function that gets the name of the weekday.

JavaScript
const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const d = new Date(); //the last expression is the return value and must evaluate to a String
ocpReturn(weekday[d.getDay()]); //this will return a value from the array above

A JS function created under the User Functions tab can be called from everywhere in the specific miniApp, such as prompts in all miniApps, web service settings in Web Service miniApp using the mustache notation {{userFunctionName}}, or an output path in a Web Service miniApp.

Do not use the return keyword to return the script's result. Use ocpReturn instead. However, if you use an inner function, use the return keyword within it.

In a user function we can take advantage of the params object and at the end, it returns a string value. Even if the output is an integer or an object, the output will be converted to string.

Example:

JavaScript
// calculate localHour utc + 3h
var localHour = parseInt(params.CurrentHour) + 3;
var prompt;
if (localHour < 12) {
  prompt = "Good Morning";
} else if (localHour < 18) {
  prompt = "Good Afternoon";
} else {
  prompt = "Good Evening";
}
ocpReturn(prompt);

Example with inner function:

JavaScript
function calculateLocalHour(){
  // UTC + 3h — inner functions still use return
  var hour = parseInt(params.CurrentHour) + 3;
  return hour;
}

var localHour = calculateLocalHour();
var prompt = "";

if (localHour < 12) {
  prompt = "Good Morning";
} else if (localHour < 18) {
  prompt = "Good Afternoon";
} else {
  prompt = "Good Evening";
}

ocpReturn(prompt);

Use case 1: Replace a prompt or a part of a prompt.

Example: {{getGreeting}} -> "Good Morning" or "Good afternoon" or "Good Evening".

2022-08-23_15-35-57.png

Use case 2: Replace the WS endpoint or part of it.

Example: Endpoint: https://example.com/api/filter?timeFrom={{getEpoch}} -> https://example.com/api/filter?timeFrom=1660136594

Validation functions

Validation JavaScript function can be used in the Validations tab in non-Intent miniApps like Alpha, Numeric, Alphanumeric, Amount, Date, and Text.

This feature provides the ability to choose how the data provided by the caller is validated against preset rules.

The validation JS function must always return a boolean in the end.

Use case example: Validate users input using a Javascript function.

​In a Validation Function we can take advantage of the params object especially the valueToValidate property which contains the value of the user's input, and at the end, should return a boolean. 

Example:

In the Numeric miniApp the caller said “one two three four fifty-six” so the params.valueToValidate holds the value "123456" . We need to accept numeric values with a length of 6 digits.

JavaScript
if (params.valueToValidate.length == 6) {
  ocpReturn(true);
} else {
  ocpReturn(false);
}

or simpler

JavaScript
ocpReturn(params.valueToValidate.length == 6);

Output functions

The Output function is available under Output tab in Web Service and Intelli miniApps. Web Service or Intelli miniApp are capable of returning multiple string values or JSON objects to our application.

Output function should return an object.

Example:

JavaScript
var result;
if (params.wsResponseCode == "200") {
  result = {
    output1: "success",
    output2: params.wsResponseBody.balanceDetails.balance,
    output3: params.wsResponseBody.balanceDetails.dueDate,
    output4: params.wsResponseBody.balanceDetails.minimumPayment,
  };
} else {
  result = {
    output1: "fail",
    output2: "unknownValue",
    output3: "unknownValue",
    output4: "unknownValue"
  };
}
ocpReturn(result);

While configuring our miniApp’s inputs and outputs through Orchestrator®, we can select to which application’s field each output will be assigned.

Do not use the return keyword to return the script's result. Use ocpReturn instead. However, if you use an inner function, use the return keyword within it.

Use case example: Parse the output body of a Web Service call and return values to the Orchestrator® app.

Response code from Web Service call: 200

Response body from Web Service call:

JavaScript
{
cardType: “credit”,
cardNetwork: “visa”,
balanceDetails: {
  balance: 1234.56,
  dueDate: “2022-12-23”,
  minimumPayment: 123.45
  }
}

Output Function:

JavaScript
var result;
if (params.wsResponseCode == "200") {
	result = {
		output1: "success",
		output2: params.wsResponseBody.balanceDetails.balance,
		output3: params.wsResponseBody.balanceDetails.dueDate,
		output4: params.wsResponseBody.balanceDetails.minimumPayment,
	};
}else {
	result = {
		output1: "fail",
		output2: "unknownValue",
		output3: "unknownValue",
		output4: "unknownValue"
	};
}	
ocpReturn(result);


Finally, if you need to consider the Web Service or Intelli miniApp invocations as failed, you can add the FailExitReason property in the output object like the example below.

JavaScript
var result;
if (params.wsResponseCode == "200") {
	result = {
		output1: "success",
		output2: params.wsResponseBody.balanceDetails.balance,
		output3: params.wsResponseBody.balanceDetails.dueDate,
		output4: params.wsResponseBody.balanceDetails.minimumPayment,
	}; 
}else {
	var errorMessage;
	switch (params.wsResponseCode) {
		case "400": 
			errorMessage = "BAD_REQUEST";
			break;
		case "401": 
			errorMessage = "UNAUTHORIZED";
			break;
		case "404": 
			errorMessage = "NOT_FOUND";
			break;
		case "500": 
			errorMessage = "INTERNAL_SERVER_ERROR";
			break;
		default:
			errorMessage = "UNKNOWN_ERROR";
			break;
​}
	result = {
		output1: "fail",
		output2: "unknownValue",
		output3: "unknownValue",
		output4: "unknownValue",
		FailExitReason: errorMessage
	};
}
ocpReturn(result);

Node Version

Node.js v20. The ECMAScript compatibility can be found in this table.

Params Object

To access any of the available properties through a JS function, you need to use the dot (.) notation within the function.

Example:

To get the value of the ANI:

params.Ani

Properties

miniApp details

Property

Description

Example Value

miniAppUID

The group the miniApp belongs to


miniAppName

The short name of the miniApp

AskIntent

accountId

The creator's ID

1234abc-567d-890e-123f-456789ghijkl

miniApp-appId

The full ID of the miniApp

1234abc-567d-890e-123f-456789ghijkl.AskIntent.Insurance.MiniApps.groupname

Session details

Property

Description

Example Value

Ani

Automatic Number Identification, the caller’s phone number


Dnis

Dialed Number Identification Service, the phone number that user called


Locale

The session’s locale

en-US

ConnectionID

IVR Related ID


DialogGroupID

A common ID for all miniApp invocations of a single dialog


DialogID

A unique ID for each dialog and miniApp invocation


testMode

Turns session in testMode

true

step

The number of the step in dialog


Timestamp

Timestamp in ISO format

1970-01-01T00:00:00.000

CurrentHour

The hour’s value in UTC

14

CurrentTime

The minutes’ value

59

AgentRequests

Number of times the caller asked for a representative within dialog


NoMatches

Number of NoMatch events during dialog


NoInputs

Number of NoInput events during dialog


Errors

Total number of errors during dialog


ClosingRequestFlag

The caller confirmed that they don’t have any further requests

Bot: Your current balance is $12.34. Is there anything else I can do for you?

   User: No, that will be all

SameStateEvents

Counts the number of times where the user’s input didn’t evolve the dialog


Rejections

Counts the number of times a user rejected the value in a confirmation step


RejectedInput

The value of the input rejected by the user or failed to pass validation


WrongInput

Counts the number of invalid inputs


InputMode

indicates how the user entered a value

text, DTMF, Voice

Special properties

Property

Description

Example value

validationFailReason

Indicates the failed validation type

preBuiltFailed-CreditCard

validationResult

Indicates whether the validation was successful or not

success/fail

valueToValidate

Holds the value of the user’s input for non-Intent miniApps.

Can be used in validations step if Javascript validation is enabled.


wsResponseBody

Contains the entire Web Service call response body.

Available only in Web Service miniApps


wsResponseCode

Holds the Web Service call response code.

Available only in Web Service miniApps

200, 400, 404, 500

wsResponseHeaders


An array of objects. Each object has a name and a value.

JavaScript
[
  {name:"testName1",value:"testValue1"},
  {name:"testName2",value:"testValue2"}
]

miniApps inputs

Each miniApp can receive input from the parent application (Orchestrator® or directly from the Contact Center).

Inputs can be strings or JSON objects

To access these inputs, one can use the following properties of the params object:

  • extValue1

  • extValue2

  • extValue3

  • extValueN

Logging in JS functions

A developer can log messages within JS functions using the print() and console.log() functions.

The logs can be found in miniApp's log file for each distinct invocation.

Do not log sensitive information.

Example:

console.log("I am logging a message");

Response Headers display

Response Headers display is available in WebService and Intelli miniApps.

You have the ability to view the response headers, just like the response body, so you can utilize their data.

The application proceeds to send these response headers as an array of objects, each containing a header name and its respective value, to the js-api.

Here's a sample representation of the response headers:

JavaScript
params.wsResponseHeaders = [
  {name:"testName1",value:"testValue1"},
  {name:"testName2",value:"testValue2"},
  {name:"testName2",value:"anotherValueOfTestName2"},
]

This essentially means, for instance, if the response carries the header with the key testName1 and value testValue1, user will be capable of reading this header with the help of js-code.

The below snippet is an illustration of how you can do that:

JavaScript
const valueOfTestHeader = params.wsResponseHeaders.find(header => header.name === "testName1").value;
console.log(valueOfTestHeader);
ocpReturn("The value of testName1 header is " + valueOfTestHeader);

In this scenario, testName1 is the name of the header and the code fetches its corresponding value.

Handlebars Library

Handlebars library is supported for js-api, in Isolated modes.

The below snippet is an illustration of how you can do that:

Isolated mode

JavaScript
// compile the template 
const template = Handlebars.compile("Handlebars {{doesWhat}}"); 
// execute the compiled template 
ocpReturn(template({ doesWhat: "rocks!" }));

Eta Library

Eta Library is supported for js-api in Isolated modes.

The below snippet is an example illustration of how you can do that:

Isolated Mode

JavaScript
const etaInstance = new eta.Eta(); 
ocpReturn(etaInstance.renderString("Hello <%= it.name %>", { name: "Ben" }))

parseXML Function

Parses an XML string and returns the corresponding parsed JSON object. In this way a webService miniApp can support SOAP (Simple Object Access Protocol) APIs.

Parameter

Type

Description

xmlString

string

The XML string to be parsed

options

object

(Optional) Configuration options passed to the fast-xml-parser XMLParser constructor. See available options here.

processEntities option is set to false by default for security reasons and cannot be enabled.

Examples

  • Simple parsing

JavaScript
const xml = `<soapenv:Envelope xmlns:fin="http://www.abc.def.123.com/findby" xmlns:com="http://www.abc.def.symitar.com/common/dto/common" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header />
    <soapenv:Body>
        <fin:findBySSN>
            <Request com:MessageId="?">
                <SSN>123123123123</SSN>
                <DeviceInformation DeviceType="OMILIA_UAT" DeviceNumber="20008" />
                <Credentials com:ProcessorUser="0">
                    <AdministrativeCredentials>
                        <Password>*123abc#$</Password>
                    </AdministrativeCredentials>
                </Credentials>
            </Request>
        </fin:findBySSN>
    </soapenv:Body>
</soapenv:Envelope>`
const parsed = parseXML(xml);
ocpReturn(parsed['soapenv:Envelope']['soapenv:Body']['fin:findBySSN']['Request']['SSN']) //123123123123
  • Parsing with options

JavaScript
const options = {
  ignoreAttributes: false,
  attributeNamePrefix: '@_'
};
const json = parseXML('<tag attr="value">content</tag>', options);
console.log(JSON.stringify(json));
// {
//   tag: {
//     '@_attr': 'value',
//     '#text': 'content'
//   }
// }
json.tag['@_attr'] //value

signJwt Function

The signJwt function is a utility designed to create a signed JSON Web Token (JWT) using the jsonwebtoken library's sign function. This function is essential for secure data exchange, allowing you to encode information (like user data) in a compact and URL-safe format that can be verified and trusted.

Parameter

Type

Description

payload

object

This parameter contains the data you want to include in the token. Typically, it includes information like the user ID or other claims relevant to the token's purpose

Secret

string

This is a secret key used to cryptographically sign the token. It ensures the token's integrity and authenticity, and it must be kept secure

Options

Object

Contains additional settings for token generation. Common options include:

  • expiresIn: Specifies the token's validity duration (e.g., '1h' for 1 hour).

  • algorithm: Determines the signing algorithm used, such as HS256

The function returns a signed JWT string, which can be used for authentication purposes or to securely transmit the included data.

Example Usage:

Here is a quick example demonstrating how to use the signJwt function:

JavaScript
const token = signJwt({ userId: 123 }, 'mySecret', { expiresIn: '1h' });

In this example, a JWT is created with a payload containing a user ID (userId: 123), signed with the secret key 'mySecret', and set to expire in one hour. The resulting token string can then be used in various security contexts such as authentication headers or URL parameters.

Testing a JS function

OCP® text editor allows the developer to test a function before even saving it. To do so, write your function, set the additional parameters under the Set params line, and click the Run button.

2026-06-05_10-16-40.png

Access control
Running a JS function calls the miniapps/api/js endpoint, which is restricted to authorized users. You must hold the developer, maintainer, or owner role on the group that the miniApp belongs to. The request now includes the miniAppId; if you do not have one of these roles on that miniApp's group, the request returns 403 Forbidden.

Always return your result with ocpReturn(...). A script that ends with a bare trailing value relies on deprecated legacy behavior will fail on JS function testing.

ocpReturn function

The ocpReturn(value) explicitly defines the value a JS script returns and runs the script in isolated mode. It is required in every User, Validation, and Output function.

  • Call ocpReturn once with the final value.

  • The value type follows the function type:

    • a string for User functions,

    • a boolean for Validation functions,

    • an object for Output functions.

  • Inner helper functions still use the JavaScript return keyword; the script returns its overall result through ocpReturn.

JavaScript
var anObject={}
anObject.a ="A"
anObject.b="B"
ocpReturn(anObject);

This is the recommended method to return a result from JS execution.