spAriaUtil

The spAriaUtil API provides methods to show messages on a screen reader.

This API is an angular service that you can use in Service Portal widget client scripts.

sendLiveMessage(String message)

Announce a message to a screen reader.

The sendLiveMessage() method injects text into an aria-live region on the page. The default setting for an aria-live region is assertive, which means that messages are announced immediately. This can annoy and confuse users if used too frequently.

Parameters

NameTypeDescription
messageStringThe message to be shown.

Returns

TypeDescription
voidMethod does not return a value

Example

function(spAriaUtil) {
  /* widget controller */

  spAriaUtil.sendLiveMessage('Hello world!');
}

Version: zurich

API Reference – Client Side

ServiceNow provides client-side JavaScript APIs allowing all of you to control aspects of how ServiceNow is displayed and functions within the web browser. This reference lists available classes and methods along with parameters, descriptions, and examples to make controlling the end user experience easier.

spContextManager

Makes data from a Service Portal widget available to other applications and services in a Service Portal page. For example, pass widget data to Agent Chat when it opens in a Service Portal page.

The spContextManager API is an AngularJS service that you can use in Service Portal widget client scripts.

Keys passed to this API are unique per page. For example, if the 'agent-chat' key is already initialized by another widget on the page through the addContext() method, you must use the updateContextForKey() method to update the key’s data. Available keys include: agent-chat: Sends widget data to Agent Chat.

For more information about passing data to Agent Chat, see Configure Agent Chat in Service Portal.

addContext(String key, Object context)

Initializes a key and adds widget data as the value. For example, add data to the ‘agent-chat’ key to make it available to Agent Chat.

Use this method the first time data is added to a specific key on a Service Portal page. If the key is already used by another widget on the page, use the updateContextForKey() method instead.

Parameters

NameTypeDescription
keyStringName of the key to send the data. Available keys includeagent-chat: Sends widget data to Agent Chat when it opens in a Service Portal page.
contextObjectWidget data in JSON format to send to the application or service specified in the key parameter. For example, {'approval_count': 5}.

Returns

TypeDescription
voidMethod does not return a value

Example

Pass approval_count to Agent Chat. When a user initiates an Agent Chat conversation from the Service Portal homepage, the system appends &sysparm_approval_count=5 to the Agent Chat iframe URL.

function ($scope, spContextManager) {
    spContextManager.addContext('agent-chat', {
        'approval_count': 5       
    });
};

getContext()

Returns each key and associated data object defined by any widget on the page.

Using this method may affect performance. Use this method to understand which keys are initialized on the page and to get their current values. If you know which key you need to access, use the getContextForKey() method instead.

Returns

TypeDescription
ObjectEach key and associated data object defined on the page.

Example

function ($scope, spContextManager) {
  spContextManager.getContext();
} 

getContextForKey(String key, Boolean returnPromise)

Returns the widget data associated with a key.

Parameters

NameTypeDescription
keyStringName of the key to get context from. Available keys include: agent-chat: Sends widget data to Agent Chat.
returnPromiseBooleanFlag that determines whether to return the data associated with a key as a promise or an object. Values include: True: return the data as a promise. Use this option if another widget on the page uses the addContext() method to initialize the same key. Returning a promise prevents returning an undefined object when the key is not yet initialized. False: returns an object containing the data associated with the key.

Returns

TypeDescription
PromiseIf returnPromise is true, returns a promise that is fulfilled when another widget on the page initializes the key.
ObjectIf returnPromise is false, returns an object containing the data associated with the key. For example, {approval_count: 5}.

Example

Pass approval_count to Agent Chat. When a user initiates an Agent Chat conversation from the Service Portal homepage, the system appends &sysparm_approval_count=5 to the Agent Chat iframe URL.

function ($scope, spContextManager) {
  spContextManager.getContextForKey('agent-chat', true).then(function(context) {
    context = context || {};
    context.approval_count = 5; 
    spContextManager.updateContextForKey('agent-chat', context);
  });
} 

updateContextForKey(String key, Object context)

Sends data to an existing key. For example, if another widget on the page uses the ‘agent-chat’ key to pass data to the Agent Chat configuration, you must update the context of the key rather than using the addContext() method.

Parameters

NameTypeDescription
keyStringName of the key to send the data. Available keys includeagent-chat: Sends widget data to Agent Chat when it opens in a Service Portal page.
contextObjectWidget data in JSON format to send to the application or service specified in the key parameter. For example, {'approval_count': 5}.

Returns

TypeDescription
voidMethod does not return a value

Example

Pass approval_count to Agent Chat. When a user initiates an Agent Chat conversation from the Service Portal homepage, the system appends &sysparm_approval_count=5 to the Agent Chat iframe URL.

function ($scope, spContextManager) {
  spContextManager.getContextForKey('agent-chat', true).then(function(context) {
    context = context || {};
    context.approval_count = 5; 
    spContextManager.updateContextForKey('agent-chat', context);
  });
} 

Version: zurich

API Reference – Client Side

ServiceNow provides client-side JavaScript APIs allowing all of you to control aspects of how ServiceNow is displayed and functions within the web browser. This reference lists available classes and methods along with parameters, descriptions, and examples to make controlling the end user experience easier.

spModal

Shows alerts, prompts, and confirmation dialogs in Service Portal widgets. The spModal class is available in Service Portal client scripts.

The spModal class is a lightweight wrapper for Angular UI bootstrap’s $uibModal. You can use the spModal.open() method to display a widget in a modal dialog.

alert(String message).then(fn)

Displays an alert.

Parameters

NameTypeDescription
messageStringThe message to display.

Returns

TypeDescription
BooleanThe promise contains a single argument that contains true or false.

Example

// HTML template 
<button ng-click="c.onAlert()" class="btn btn-default">
    Alert
  </button>

// Client script
function(spModal) {
    var c = this;
  c.onAlert = function () {
        spModal.alert('How do you feel today?').then(function (answer) {
            c.simple = answer;
        });
    }
 }

confirm(String message).then(fn)

Displays a confirmation message.

Parameters

NameTypeDescription
messageStringThe message to display.

Returns

TypeDescription
BooleanThe promise contains a single argument that contains true or false.

Example

// HTML template 
 <button ng-click="c.onConfirm()" class="btn btn-default"> Confirm </button> 
<span>{{c.confirmed}}</span>   

// Client script
function(spModal) {
  var c = this;
  c.onConfirm = function() {
        c.confirmed = "asking";
        spModal.confirm("Can you confirm or deny this?").then(function(confirmed) {
            c.confirmed = confirmed; // true or false
        })
    }
 } 

Example

Confirm with HTML message:

//HTML template 
<button ng-click="c.onConfirmEx()" class="btn btn-default">
    Confirm - HTML message
  </button>
  <span>{{c.confirmed}}</span>

// Client script
function(spModal) {
  var c = this;
  // more control, passing options
    c.onConfirmEx = function() {
        c.confirmed = "asking";
        var warn = '<i class="fa fa-warning" aria-hidden="true"></i>';
        spModal.open({
            title: 'Delete this Thing?',
            message: warn + ' Are you <b>sure</b> you want to do that?'
        }).then(function(confirmed) {
            c.confirmed = confirmed;
        })
    }
}

open(Object options).then(fn)

Opens a modal window using the specified options.

Parameters

NameTypeDescription
optionsObjectAn object that may have these properties. backdrop: Boolean|String. Controls the presence of a backdrop. Valid values: true: Displays backdrop. false: No backdrop. static: Disables modal closing by selecting the backdrop. Default: true buttons: Array. Buttons to show on the dialog. The default is Cancel and OK. input: Boolean. When true, shows an input field on the dialog. Default: false keyboard: Boolean. When true, indicates that the dialog is closeable using the ESC key.Default: true message: String. HTML that goes in the header. Default: empty noDismiss: Boolean. When true, indicates that the header section containing the close icon isn’t present.Default: false shared: Client-side object. Shares data with the embedded widget client script. size: String. Size of the window. Valid values: ‘sm’ or ‘lg’. Default: empty title: String. HTML that goes in the header. Default: empty value: String. Value of the input field. Default: empty widget: String. Widget ID or sys_id to embed in the dialog. Default: empty widgetInput: Object. Sent to the embedded widget as input. Default: null

Returns

TypeDescription
voidMethod does not return a value

Example

The following code shows how to create a prompt with a label.

//HTML template
<button ng-click="c.onOpen()" class="btn btn-default">
    Prompt with label
  </button>
  <div ng-show="c.name">
    You answered <span>{{c.name}}</span>
  </div>

//Client code
function(spModal) {
  var c = this;
  c.onOpen = function() {
        //ask the user for a string
        spModal.open({
            title: 'Give me a name',
            message: 'What would you like to name it?',
            input: true,
            value: c.name
        }).then(function(name) {
            c.name = name;
        })
    }
}

Example

The following code shows how to use the custom buttons option.

//HTML template
<button ng-click="c.onAgree()" class="btn btn-default">
    Agree
  </button>
  <div ng-show="c.agree">
    You answered {{c.agree}}
  </div>

//Client script
function(spModal) {
  var c = this;
  c.onAgree = function() {
        // ask the user for a string
        // note embedded html in message
        var h = '<h4>Apple likes people to agree to lots of stuff</h4>'
        // Line feeds added to the following lines for presentation formatting.
        var m = 'Your use of Apple software or hardware products is based 
on the software license and other terms and conditions in effect for the 
product at the time of purchase. Your agreement to these terms is required 
to install or use the product. '
        spModal.open({
            title: 'Do you agree?',
            message: h + m,
            buttons: [
                {label:'✘ ${No}', cancel: true},
                {label:'✔ ${Yes}', primary: true}
            ]
        }).then(function() {
            c.agree = 'yes';
        }, function() {
            c.agree = 'no';
        })
    }
}

Example

The following code shows how to use the embedded widget option.

//HTML template
<button ng-click="c.onWidget('widget-cool-clock')" class="btn btn-default">
    Cool Clock
  </button>

//Client script
function(spModal) {
  var c = this;
  c.onWidget = function(widgetId, widgetInput) {
        spModal.open({
            title: 'Displaying widget ' + widgetId,
            widget: widgetId, 
            widgetInput: widgetInput || {}
        }).then(function(){
            console.log('widget dismissed');
        })      
    }
}

prompt(String message, String default).then(fn)

Displays a prompt for user input.

Parameters

NameTypeDescription
messageStringThe message to display.
default (optional)StringA default value to use if the user does not provide a response.

Returns

TypeDescription
StringThe promise contains the user’s response, or the default value if the user does not enter a response.

Example

//HTML template
 <button ng-click="c.onPrompt()" class="btn btn-default">
    Prompt
  </button>
  <div ng-show="c.name">
    You answered <span>{{c.name}}</span>
  </div>

// Client script
function(spModal) {
  var c = this;
  c.onPrompt = function() {
        spModal.prompt("Your name please", c.name).then(function(name) {
            c.name = name;
        })
    }
}

Version: zurich

API Reference – Client Side

ServiceNow provides client-side JavaScript APIs allowing all of you to control aspects of how ServiceNow is displayed and functions within the web browser. This reference lists available classes and methods along with parameters, descriptions, and examples to make controlling the end user experience easier.

spUtil

The spUtil API provides utility methods to perform common functions in a Service Portal widget client script.

These functions include:

For additional information on widgets, see Service Portal widgets.

addErrorMessage(String message)

Displays a notification error message.

Parameters

NameTypeDescription
messageStringError message to display.

Returns

TypeDescription
voidMethod does not return a value

Example

spUtil.addErrorMessage("There has been an error processing your request")

addInfoMessage(String message)

Displays a notification info message.

Parameters

NameTypeDescription
messageStringMessage to display.

Returns

TypeDescription
voidMethod does not return a value

Example

spUtil.addInfoMessage("Your order has been placed")

addTrivialMessage(String message)

Displays a trivial notification message.

Trivial messages disappear after a short period of time.

Parameters

NameTypeDescription
messageStringMessage to display.

Returns

TypeDescription
voidMethod does not return a value

Example

spUtil.addTrivialMessage("Thanks for your order")

createUid()

Create a unique identifier.

Returns

TypeDescription
StringA unique 32 character ID.

format(String template, Object data)

Formats a string that contains variables.

Use this method as an alternative to string concatenation.

Parameters

NameTypeDescription
templateStringString template that contains values for variable substitution.
dataObjectObject containing the values for the variables defined in the template string.

Returns

TypeDescription
StringString containing the variable values instead of the variable nomenclature.

Example

spUtil.format('An error ocurred: {error} when loading {widget}', {error: '404', widget: 'sp-widget'})
'An error occurred: 404 when loading sp-widget'

get(String widgetId Object data)

Embeds a widget model in a widget client script.

The callback function returns the full widget model. For additional information on widgets, see Service Portal widgets.

Parameters

NameTypeDescription
widgetIdStringWidget ID or sys_id of the widget to embed.
dataObjectOptional. Name/value pairs of parameters to pass to the widget model.

Returns

TypeDescription
ObjectModel of the embedded widget.

Example

Without data passed.

spUtil.get("widget-cool-clock").then(function(response) {
  c.coolClock = response;
});

Example

With data passed.

spUtil.get('pps-list-modal', {title: c.data.editAllocations, 
  table: 'resource_allocation', 
  queryString: 'GROUPBYuser^resource_plan=' + c.data.sysId, 
  view: 'resource_portal_allocations' }).then(function(response) {
    var formModal = response;
    c.allocationListModal = response;
  });  	

getHeaders()

Retrieves all headers to use for API calls.

Returns

TypeDescription
ObjectAll headers to use for API calls.

getHost()

Returns the complete host domain.

Returns

TypeDescription
StringThe complete host domain, for example hi.servicenow.com

getPreference(String preference, Function callback)

Executes the callback with User Preference response by passing the preference name.

Parameters

NameTypeDescription
preferenceStringName of the preference.
callbackFunctionDefine the callback function.

Returns

TypeDescription
voidMethod does not return a value

getURL()

Returns the current service portal URL information.

Returns

TypeDescription
StringCurrent service portal URL.

isMobile()

Checks if the current client is a mobile device.

Returns

TypeDescription
BooleanFlag that indicates whether the current client is a mobile device.Valid values: true: Current client is a mobile device. false: Current client is not a mobile device.

parseAttributes(String attributes)

Parses the comma-separated attributes within a specified string.

Parameters

NameTypeDescription
attributesStringString containing comma separated attributes, such as the Attributes field of a dictionary record.

Returns

TypeDescription
ArrayArray of objects containing the parsed attributes.

Example

function getRefQualElements() {
  var refQualElements = [];
  if (field && field.attributes && field.attributes.indexOf('ref_qual_elements') > -1) {
    var attributes = spUtil.parseAttributes(field.attributes);
    refQualElements = attributes['ref_qual_elements'].split(';');
  }
  return refQualElements;
}

recordWatch(Object $scope, String table, String filter, Function callback)

Watches for updates to a table or filter and returns the value from the callback function.

Allows a widget developer to respond to table updates in real-time. For instance, by using recordWatch(), the Simple List widget can listen for changes to its data table. If records are added, removed, or updated, the widget updates automatically.

Note: When passing the $scope argument into the recordWatch() function, inject $scope into the parameters of your client script function.

Parameters

NameTypeDescription
$scopeObjectScope of the data object updated by the callback function.
tableStringWatched table.
filterStringFilter for fields to watch.
callbackFunctionOptional. Parameter to define the callback function.

Returns

TypeDescription
PromiseReturn value of the callback function.

Example

//A simple recordWatch function.
spUtil.recordWatch($scope, "live_profile", "sys_id=" + liveProfileId);

//In a widget client script
function(spUtil, $scope) {
  /* widget controller */
  var c =this;

  // Registers a listener on the incident table with the filter active=true, 
  // meaning that whenever something changes on that table with that filter, 
  // the callback function is executed.    
  // The callback function takes a single parameter 'response', which contains 
  // the property 'data'. The 'data' property contains information about the changed record. 
  spUtil.recordWatch($scope, "incident", "active=true", function(response) {
        
    // Returns the data inserted or updated on the table 
    console.log(response.data);   
    
    });
}

refresh(Object $scope)

Calls the server and replaces the current options and data with the server response.

Calling spUtil.refresh() is similar to calling server.refresh(). However, when you call spUtil.refresh(), you can define the $scope object.

Parameters

NameTypeDescription
$scopeObjectScope defined for the update.

Returns

TypeDescription
ObjectUpdated options and data objects.

scrollTo(String selector, Number time)

Scrolls to the element with the specified selector, over a specified period of time.

Parameters

NameTypeDescription
selectorStringSelector to scroll to.
timeNumberTime taken to scroll to the specified selector.Unit: Milliseconds

Returns

TypeDescription
voidMethod does not return a value

setBreadCrumb(Object $scope, Array breadcrumbs)

Updates the header breadcrumbs.

Parameters

NameTypeDescription
$scopeObjectScope defined for the table.
breadcrumbsArrayConditions used to create the breadcrumb filter.

Returns

TypeDescription
voidMethod does not return a value

setPreference(String pref, String value)

Sets a user preference.

Parameters

NameTypeDescription
prefStringPreference name
valueStringPreference value

Returns

TypeDescription
voidMethod does not return a value

setSearchPage(String searchPage)

Updates the search page.

Parameters

NameTypeDescription
searchPageStringName of the search page.

Returns

TypeDescription
voidMethod does not return a value

update(Object $scope)

Updates the data object on the server within a given scope.

This method is similar to server.update(), but includes a $scope parameter that defines the scope to pass over.

Parameters

NameTypeDescription
$scopeObjectScope defined for the update.

Returns

TypeDescription
ObjectUpdated data object.

Example

The following includes a P1 widget that watches for changes to the state field and uses a filter to watch all active P1s and let the callback function determine whether to refresh the data. The data.changes property contains an array of any updated fields. If the state of any fields have changed, the data is updated in the widget.

var q = "priority=1^active=true^EQ";
spUtil.recordWatch($scope, "incident", q, function(event, data) {
   if (data.changes.includes("state")) { // only update if state was updated.
      spUtil.update($scope);
   }
});