### Embed Widgets and Get Server Data with spUtil Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Methods for embedding other Service Portal widgets or fetching their models. `get` can fetch a widget model, optionally with data, and returns a promise. This is useful for dynamically loading or interacting with other widgets. ```javascript spUtil.get("widget-cool-clock").then(function(response) { c.coolClock = response; }); ``` ```javascript 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; }); ``` -------------------------------- ### spUtil - User Preferences and Data Management Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Methods for getting and setting user preferences, updating server data, and watching for record changes. ```APIDOC ## spUtil.getPreference(String preference, Function callback) ### Description Executes the callback with User Preference response by passing the preference name. ### Method client script function ### Endpoint N/A ### Parameters * **preference** (String) - The name of the user preference to retrieve. * **callback** (Function) - The function to execute with the preference value. ### Response N/A ## spUtil.setPreference(String pref, String value) ### Description Sets a user preference. ### Method client script function ### Endpoint N/A ### Parameters * **pref** (String) - The name of the preference to set. * **value** (String) - The value to set for the preference. ### Response N/A ## spUtil.update(Object $scope) ### Description Updates the data object on the server within a given scope. ### Method client script function ### Endpoint N/A ### Parameters * **$scope** (Object) - The scope object for the widget. ### Response N/A ## spUtil.recordWatch(Object $scope, String table, String filter, Function callback) ### Description Watches for updates to a table or filter and returns the value from the callback function. ### Method client script function ### Endpoint N/A ### Parameters * **$scope** (Object) - The scope object for the widget. * **table** (String) - The name of the table to watch. * **filter** (String) - The filter to apply to the table. * **callback** (Function) - The function to execute when a change is detected. ### Response N/A ``` -------------------------------- ### Get All Context Data with spContextManager (JavaScript) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spContextManager.getContext() method retrieves all initialized keys and their associated data objects currently defined by widgets on the page. Use this to understand the page's context state. Be aware that its usage may impact performance; prefer getContextForKey() for specific data retrieval. ```javascript function($scope, spContextManager) { spContextManager.getContext(); } ``` -------------------------------- ### Get Specific Context Data with spContextManager (JavaScript) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spContextManager.getContextForKey() method retrieves widget data associated with a specific key. It can return data directly as an object or as a promise if the 'returnPromise' parameter is set to true, which resolves when the key is initialized by another widget. This is useful for accessing specific data points, like 'approval_count' for Agent Chat. ```javascript function($scope, spContextManager) { spContextManager.getContextForKey('agent-chat', true).then(function(context) { context = context || {}; context.approval_count = 5; spContextManager.updateContextForKey('agent-chat', context); }); } ``` -------------------------------- ### Scroll to Element with Animation - JavaScript Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The scrollTo function animates scrolling to a specific element identified by a CSS selector over a defined duration. This is useful for guiding user attention within the page. ```javascript spUtil.scrollTo(selector, time); ``` -------------------------------- ### spUtil - Server and Environment Information Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Methods to retrieve headers, host domain, URL information, and check device type. ```APIDOC ## spUtil.getHeaders() ### Description Retrieves all headers to use for API calls. ### Method client script function ### Endpoint N/A ### Parameters N/A ### Response Returns an object containing all headers. ## spUtil.getHost() ### Description Returns the complete host domain. ### Method client script function ### Endpoint N/A ### Parameters N/A ### Response * **String**: The complete host domain, for example `hi.servicenow.com`. ## spUtil.getURL() ### Description Returns the current service portal URL information. ### Method client script function ### Endpoint N/A ### Parameters N/A ### Response Returns an object containing URL information. ## spUtil.isMobile() ### Description Checks if the current client is a mobile device. ### Method client script function ### Endpoint N/A ### Parameters N/A ### Response * **Boolean**: `true` if the client is a mobile device, `false` otherwise. ``` -------------------------------- ### Service Portal Modals - Prompt Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Shows how to use the `spModal.prompt` function to display a modal dialog that asks the user for text input, returning the input value via a promise. ```APIDOC ## POST /spModal/prompt ### Description Displays a modal dialog prompting the user to enter text. The entered value is returned via a promise, allowing for client-side scripting to capture and use the user's input. ### Method POST ### Endpoint /spModal/prompt ### Parameters #### Arguments - **message** (String) - Required - The prompt message displayed to the user. - **defaultValue** (String) - Optional - The default value pre-filled in the input field. ### Example ```javascript // Client script function to trigger a prompt function(spModal) { var c = this; c.onPrompt = function() { spModal.prompt("Your name please", c.name).then(function(name) { c.name = name; }) } } ``` ### Response #### Success Response (200) The promise resolves with the string value entered by the user in the prompt, or `null` if the prompt was cancelled or dismissed without input. ``` -------------------------------- ### spUtil - UI and Display Helpers Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Methods for parsing attributes, scrolling, updating breadcrumbs, and search pages. ```APIDOC ## spUtil.parseAttributes(String attributes) ### Description Parses the comma-separated attributes within a specified string. ### Method client script function ### Endpoint N/A ### Parameters * **attributes** (String) - The string containing comma-separated attributes. ### Request Example ```javascript 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; } ``` ### Response Returns an object where keys are attribute names and values are attribute values. ## spUtil.scrollTo(String selector, Number time) ### Description Scrolls to the element with the specified selector, over a specified period of time. ### Method client script function ### Endpoint N/A ### Parameters * **selector** (String) - The CSS selector for the element to scroll to. * **time** (Number) - The duration of the scroll animation in milliseconds. ### Response N/A ## spUtil.setBreadCrumb($scope, Array breadcrumbs) ### Description Updates the header breadcrumbs. ### Method client script function ### Endpoint N/A ### Parameters * **$scope** (Object) - The scope object for the widget. * **breadcrumbs** (Array) - An array of breadcrumb objects, each with `label` and `url` properties. ### Response N/A ## spUtil.setSearchPage(String searchPage) ### Description Updates the search page. ### Method client script function ### Endpoint N/A ### Parameters * **searchPage** (String) - The name or ID of the search page to set. ### Response N/A ## spUtil.refresh($scope) ### Description Calls the server and replaces the current options and data with the server response. ### Method client script function ### Endpoint N/A ### Parameters * **$scope** (Object) - The scope object for the widget. ### Response N/A ``` -------------------------------- ### Open Modal Dialog with Input using spModal Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Demonstrates using `spModal.open()` to create a modal dialog that prompts the user for text input. The `input: true` option enables the text field, and the `value` option pre-populates it. The promise resolves with the user's input. Requires `spModal` injection. ```html //HTML template
You answered {{c.name}}
``` ```javascript //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; }) } } ``` -------------------------------- ### Retrieve Service Portal Information with spUtil Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Functions to retrieve essential information about the current Service Portal environment. `getHeaders` provides API headers, `getHost` returns the domain, `getURL` provides the current portal URL, and `isMobile` checks for mobile device access. ```javascript var apiHeaders = spUtil.getHeaders(); ``` ```javascript var hostDomain = spUtil.getHost(); // Example: 'hi.servicenow.com' ``` ```javascript var portalUrlInfo = spUtil.getURL(); ``` ```javascript var isMobileDevice = spUtil.isMobile(); ``` -------------------------------- ### Parse Attributes and Watch Records with spUtil Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Utility for parsing string attributes and setting up real-time data watches. `parseAttributes` converts a comma-separated attribute string into an object, and `recordWatch` monitors table changes and executes a callback. ```javascript 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; } ``` ```javascript spUtil.recordWatch($scope, 'incident', 'active=true', function(serverData) { // Callback function to process record updates console.log('Incident updated:', serverData); }); ``` -------------------------------- ### Initialize Context with spContextManager (JavaScript) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spContextManager.addContext() method initializes a key and associates widget data with it, making it available to other Service Portal applications like Agent Chat. This method should be used only when the key is not already in use on the page. It takes a string key and a JSON object as parameters. ```javascript function($scope, spContextManager) { spContextManager.addContext('agent-chat', { 'approval_count': 5 }); }; ``` -------------------------------- ### Manage User Preferences with spUtil Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Functions for interacting with user preferences. `getPreference` retrieves a user preference asynchronously via a callback, while `setPreference` allows setting a user preference value. ```javascript spUtil.getPreference('user_language', function(preferenceValue) { console.log('User language preference:', preferenceValue); }); ``` ```javascript spUtil.setPreference('theme', 'dark'); ``` -------------------------------- ### Display Confirmation Dialog using spModal Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Uses `spModal.confirm()` to display a confirmation message, allowing the user to confirm or deny an action. The promise resolves to a boolean indicating the user's choice. Requires `spModal` injection. Also demonstrates how to use `spModal.open()` with custom options for more complex dialogs including HTML content. ```html {{c.confirmed}} ``` ```javascript 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 }) } } ``` ```html //HTML template {{c.confirmed}} ``` ```javascript // Client script function(spModal) { var c = this; // more control, passing options c.onConfirmEx = function() { c.confirmed = "asking"; var warn = ''; spModal.open({ title: 'Delete this Thing?', message: warn + ' Are you sure you want to do that?' }).then(function(confirmed) { c.confirmed = confirmed; }) } } ``` -------------------------------- ### spUtil - Data Manipulation and Utility Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Methods for creating unique identifiers, formatting strings, embedding widgets, and retrieving server data. ```APIDOC ## spUtil.createUid() ### Description Creates a unique identifier. ### Method client script function ### Endpoint N/A ### Parameters N/A ### Response Returns a unique string identifier. ## spUtil.format(String template, Object data) ### Description Formats a string that contains variables. Use this method as an alternative to string concatenation. ### Method client script function ### Endpoint N/A ### Parameters * **template** (String) - The template string containing variables in the format {variable}. * **data** (Object) - An object containing key-value pairs for the variables. ### Request Example ```javascript spUtil.format('An error ocurred: {error} when loading {widget}', {error: '404', widget: 'sp-widget'}); ``` ### Response Returns the formatted string. ## spUtil.get(String widgetId, Object data) ### Description Embeds a widget model in a widget client script. The callback function returns the full widget model. ### Method client script function ### Endpoint N/A ### Parameters * **widgetId** (String) - The ID of the widget to embed. * **data** (Object) - Optional. Data to pass to the widget. ### Request Example Without data passed: ```javascript spUtil.get("widget-cool-clock").then(function(response) { c.coolClock = response; }); ``` With data passed: ```javascript 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; }); ``` ### Response Returns a promise that resolves with the widget model. ``` -------------------------------- ### Service Portal Modals - Custom Buttons Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Demonstrates how to use the `spModal` service to open a modal dialog with custom buttons and handle user responses. This is useful for confirmations or multi-option dialogs. ```APIDOC ## POST /spModal/open (Custom Buttons) ### Description Opens a modal dialog with custom buttons, allowing for user interaction and response handling. This is commonly used for confirmations or scenarios requiring user input through predefined choices. ### Method POST ### Endpoint /spModal/open ### Parameters #### Request Body - **title** (String) - Required - The title of the modal dialog. - **message** (String) - Required - The main content message of the modal, can include HTML. - **buttons** (Array) - Required - An array of button objects, each with `label` and optionally `cancel` or `primary` properties. ### Request Example ```json { "title": "Do you agree?", "message": "

Apple likes people to agree to lots of stuff

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.", "buttons": [ {"label": "✘ No", "cancel": true}, {"label": "\"" Yes", "primary": true} ] } ``` ### Response #### Success Response (200) Upon user interaction, the modal's promise resolves with the selected button's action (e.g., `true` for primary, `false` for cancel) or rejects if dismissed. #### Response Example ```json // Callback function after button click (function(spModal) { var c = this; c.onAgree = function() { spModal.open({ title: 'Do you agree?', message: 'Your message here', buttons: [ {label:'No', cancel: true}, {label:'Yes', primary: true} ] }).then(function() { c.agree = 'yes'; }, function() { c.agree = 'no'; }) } })(spModal); ``` ``` -------------------------------- ### Display Alert Dialog using spModal Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Utilizes the `spModal.alert()` method to display a simple alert message to the user. The promise returned by `spModal.alert()` resolves with the user's input or confirmation. Requires `spModal` to be injected into the client script. ```html ``` ```javascript function(spModal) { var c = this; c.onAlert = function () { spModal.alert('How do you feel today?').then(function (answer) { c.simple = answer; }); } } ``` -------------------------------- ### Format Strings and Create Unique IDs with spUtil Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Utility functions for string manipulation and generating unique identifiers. `format` allows for easy string templating, while `createUid` generates a unique ID, useful for dynamic element identification. ```javascript var uniqueId = spUtil.createUid(); ``` ```javascript var formattedString = spUtil.format('An error occurred: {error} when loading {widget}', {error: '404', widget: 'sp-widget'}); ``` -------------------------------- ### Show Confirmation Modal with Custom Buttons (AngularJS) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Demonstrates how to open a modal dialog to ask the user for agreement using custom buttons with embedded HTML and images. The modal is opened via a button click in the HTML template and handled by the client script. It captures the user's response ('yes' or 'no') and updates a scope variable. ```html
You answered {{c.agree}}
``` ```javascript function(spModal) { var c = this; c.onAgree = function() { // ask the user for a string // note embedded html in message var h = '

Apple likes people to agree to lots of stuff

' // 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'; }) } } ``` -------------------------------- ### spAriaUtil API Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spAriaUtil API provides methods to show messages on a screen reader. It's an AngularJS service for Service Portal widget client scripts. ```APIDOC ## POST /spAriaUtil/sendLiveMessage ### Description Announces a message to a screen reader by injecting text into an aria-live region on the page. The default setting for an aria-live region is `assertive`, which means messages are announced immediately. ### Method POST ### Endpoint /spAriaUtil/sendLiveMessage #### Parameters ##### Query Parameters * **message** (String) - Required - The message to announce to the screen reader. ### Request Example ```javascript function(spAriaUtil) { /* widget controller */ spAriaUtil.sendLiveMessage('Hello world!'); } ``` ### Response #### Success Response (200) No specific response body documented, method execution indicates success. #### Response Example N/A ``` -------------------------------- ### setPreference Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Sets a user preference with the specified key and value. ```APIDOC ## setPreference(String pref, String value) ### Description Sets a user preference. ### Parameters * **pref** (String) - The name of the user preference. * **value** (String) - The value to set for the user preference. ``` -------------------------------- ### Service Portal Modals - Embedded Widget Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Illustrates how to open a modal dialog that embeds another Service Portal widget. This allows for dynamic content display within a modal context. ```APIDOC ## POST /spModal/open (Embedded Widget) ### Description Opens a modal dialog and embeds a specified Service Portal widget within it. This feature is useful for displaying dynamic content, forms, or custom interfaces directly within a modal. ### Method POST ### Endpoint /spModal/open ### Parameters #### Request Body - **title** (String) - Required - The title displayed in the modal header. - **widget** (String) - Required - The ID of the Service Portal widget to embed. - **widgetInput** (Object) - Optional - An object containing input data to be passed to the embedded widget. ### Request Example ```json { "title": "Displaying widget cool-clock", "widget": "widget-cool-clock", "widgetInput": {} } ``` ### Response #### Success Response (200) Upon dismissal of the modal, the promise resolves with a 'widget dismissed' message. #### Response Example ```json // Client script function to open a widget in a modal 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'); }) } } ``` ``` -------------------------------- ### spModal API Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spModal class allows you to display alerts, prompts, and confirmation dialogs within Service Portal widgets. It's a wrapper for Angular UI bootstrap's $uibModal and can be used in Service Portal client scripts. ```APIDOC ## spModal.alert(String message).then(fn) ### Description Displays a simple alert message to the user. ### Method `spModal.alert` ### Parameters - **message** (String) - The message to display in the alert. ### Returns A promise that resolves with the user's input or confirmation. ### Request Example ```javascript // Client script function(spModal) { var c = this; c.onAlert = function () { spModal.alert('How do you feel today?').then(function (answer) { c.simple = answer; }); } } ``` ``` ```APIDOC ## spModal.confirm(String message).then(fn) ### Description Displays a confirmation message with 'OK' and 'Cancel' buttons. ### Method `spModal.confirm` ### Parameters - **message** (String) - The message to display in the confirmation dialog. ### Returns A promise that resolves to `true` if the user clicks 'OK', and `false` if the user clicks 'Cancel'. ### Request Example ```javascript // 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 with HTML message ```javascript // Client script function(spModal) { var c = this; c.onConfirmEx = function() { c.confirmed = "asking"; var warn = ''; spModal.open({ title: 'Delete this Thing?', message: warn + ' Are you sure you want to do that?' }).then(function(confirmed) { c.confirmed = confirmed; }) } } ``` ``` ```APIDOC ## spModal.open(Object options).then(fn) ### Description Opens a modal window with custom options, including input fields. ### Method `spModal.open` ### Parameters - **options** (Object) - An object containing configuration for the modal. - **title** (String) - The title of the modal window. - **message** (String) - The main message content of the modal. - **input** (Boolean) - If true, displays an input field in the modal. - **value** (String) - The initial value for the input field, if `input` is true. ### Returns A promise that resolves with the user's input or confirmation. ### Request Example ```javascript // 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; }) } } ``` ``` -------------------------------- ### refresh Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Calls the server and replaces the current options and data with the server response. Similar to server.refresh() but allows defining the $scope object. ```APIDOC ## refresh(Object $scope) ### Description 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 * **$scope** (Object) - The scope object for the widget. ``` -------------------------------- ### Send Live Message with spAriaUtil (JavaScript) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spAriaUtil.sendLiveMessage() method announces a message to screen readers by injecting text into an assertive aria-live region. Use this for immediate feedback but avoid frequent use to prevent user annoyance. It's an AngularJS service usable in Service Portal widget client scripts. ```javascript function($scope, spAriaUtil) { /* widget controller */ spAriaUtil.sendLiveMessage('Hello world!'); } ``` -------------------------------- ### setSearchPage Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Updates the search page used by the portal. ```APIDOC ## setSearchPage(String searchPage) ### Description Updates the search page. ### Parameters * **searchPage** (String) - The name or ID of the search page to set. ``` -------------------------------- ### Update UI Elements and Server Data with spUtil Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Functions for updating the user interface and server-side data. `refresh` reloads the widget's data from the server, `scrollTo` scrolls to a specific element, `setBreadCrumb` updates navigation, `setSearchPage` changes the search results page, and `update` modifies the data object on the server. ```javascript spUtil.refresh($scope); ``` ```javascript spUtil.scrollTo('#section-id', 500); ``` ```javascript spUtil.setBreadCrumb($scope, [{label: 'Home', url: '/sp'}, {label: 'My Tickets'}]); ``` ```javascript spUtil.setSearchPage('sc_cat_item'); ``` ```javascript spUtil.update($scope); ``` -------------------------------- ### spUtil - Message Notifications Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Methods to display notification messages in Service Portal. ```APIDOC ## spUtil.addErrorMessage(String message) ### Description Displays a notification error message. ### Method client script function ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript spUtil.addErrorMessage("There has been an error processing your request"); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ## spUtil.addInfoMessage(String message) ### Description Displays a notification info message. ### Method client script function ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript spUtil.addInfoMessage("Your order has been placed"); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ## spUtil.addTrivialMessage(String message) ### Description Displays a trivial notification message. Trivial messages disappear after a short period of time. ### Method client script function ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript spUtil.addTrivialMessage("Thanks for your order"); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Display Notification Messages using spUtil Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index These methods are used to display notification messages to the user within the Service Portal. They include options for error, info, and trivial messages, which disappear after a short time. ```javascript spUtil.addErrorMessage("There has been an error processing your request"); ``` ```javascript spUtil.addInfoMessage("Your order has been placed"); ``` ```javascript spUtil.addTrivialMessage("Thanks for your order"); ``` -------------------------------- ### spContextManager API Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spContextManager API makes data from a Service Portal widget available to other applications and services on a Service Portal page. It's an AngularJS service for widget client scripts. ```APIDOC ## POST /spContextManager/addContext ### Description Initializes a key and adds widget data as the value. 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, use `updateContextForKey()` instead. ### Method POST ### Endpoint /spContextManager/addContext #### Parameters ##### Query Parameters * **key** (String) - Required - Name of the key to send the data. Available keys include `agent-chat`. * **context** (Object) - Required - Widget data in JSON format. Example: `{'approval_count': 5}`. ### Request Example ```javascript function ($scope, spContextManager) { spContextManager.addContext('agent-chat', { 'approval_count': 5 }); }; ``` ### Response #### Success Response (200) No specific response body documented, method execution indicates success. #### Response Example N/A ``` ```APIDOC ## GET /spContextManager/getContext ### Description Returns each key and associated data object defined by any widget on the page. Using this method may affect performance; use `getContextForKey()` if you know the specific key you need. ### Method GET ### Endpoint /spContextManager/getContext ### Parameters None ### Request Example ```javascript function ($scope, spContextManager) { spContextManager.getContext(); } ``` ### Response #### Success Response (200) * **Object** - An object containing all initialized keys and their associated data. #### Response Example ```json { "agent-chat": { "approval_count": 5 } } ``` ``` ```APIDOC ## GET /spContextManager/getContextForKey ### Description Returns the widget data associated with a specific key. ### Method GET ### Endpoint /spContextManager/getContextForKey #### Parameters ##### Query Parameters * **key** (String) - Required - The name of the key to retrieve data for. * **returnPromise** (Boolean) - Required - If true, returns a promise that is fulfilled when the key is initialized. If false, returns the data object directly. ### Request Example ```javascript function ($scope, spContextManager) { spContextManager.getContextForKey('agent-chat', true).then(function(context) { context = context || {}; context.approval_count = 5; spContextManager.updateContextForKey('agent-chat', context); }); } ``` ### Response #### Success Response (200) * **Promise** - If `returnPromise` is true, a promise fulfilled with the data object. * **Object** - If `returnPromise` is false, an object containing the data associated with the key. Example: `{approval_count: 5}`. #### Response Example ```json { "approval_count": 5 } ``` ``` ```APIDOC ## POST /spContextManager/updateContextForKey ### Description Sends data to an existing key. Use this method if another widget on the page already uses the specified key. ### Method POST ### Endpoint /spContextManager/updateContextForKey #### Parameters ##### Query Parameters * **key** (String) - Required - Name of the key to update. Available keys include `agent-chat`. * **context** (Object) - Required - Widget data in JSON format to send to the application or service. Example: `{'approval_count': 5}`. ### Request Example ```javascript function ($scope, spContextManager) { spContextManager.updateContextForKey('agent-chat', { 'approval_count': 6 }); }; ``` ### Response #### Success Response (200) No specific response body documented, method execution indicates success. #### Response Example N/A ``` -------------------------------- ### Show User Prompt with Default Value (AngularJS) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Illustrates how to display a modal dialog that prompts the user for input with a pre-filled default value. Clicking a button in the HTML template calls the client script function, which uses `spModal.prompt`. The entered value is then assigned to the `c.name` scope variable upon user confirmation. ```html
You answered {{c.name}}
``` ```javascript function(spModal) { var c = this; c.onPrompt = function() { spModal.prompt("Your name please", c.name).then(function(name) { c.name = name; }) } } ``` -------------------------------- ### recordWatch Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Watches for updates to a specified table and filter. The callback function is executed when changes are detected, allowing for real-time UI updates. ```APIDOC ## recordWatch(Object $scope, String table, String filter, Function callback) ### Description 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 * **$scope** (Object) - The scope object for the widget. * **table** (String) - The name of the table to watch. * **filter** (String) - The filter to apply to the table records. * **callback** (Function) - The function to execute when changes are detected. It receives 'response' and 'data' as arguments. ### Request Example ```javascript //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); }); } ``` ### Request Example (Advanced) ```javascript 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); } }); ``` ``` -------------------------------- ### scrollTo Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Scrolls to the element with the specified selector over a given period of time. ```APIDOC ## scrollTo(String selector, Number time) ### Description Scrolls to the element with the specified selector, over a specified period of time. ### Parameters * **selector** (String) - The CSS selector for the element to scroll to. * **time** (Number) - The duration of the scroll animation in milliseconds. ``` -------------------------------- ### update Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Updates the data object on the server within a given scope. Similar to server.update() but includes a $scope parameter. ```APIDOC ## update(Object $scope) ### Description 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 * **$scope** (Object) - The scope object for the widget. ``` -------------------------------- ### Set User Preference - JavaScript Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The setPreference function allows for setting a specific user preference with a given value. This can be used to personalize user experience or store session-specific data. ```javascript spUtil.setPreference(pref, value); ``` -------------------------------- ### Display Embedded Widget in Modal (AngularJS) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Shows how to open a modal window that displays a specified ServiceNow widget. A button in the HTML template triggers the client script function, which uses `spModal.open` to render the widget identified by `widgetId`. An optional `widgetInput` object can be passed to the widget. ```html ``` ```javascript 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'); }) } } ``` -------------------------------- ### Update Search Page - JavaScript Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The setSearchPage function updates the currently active search page. This is typically used to redirect the user to a different search results view. ```javascript spUtil.setSearchPage(searchPage); ``` -------------------------------- ### Watch Table Records for Updates - JavaScript Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The recordWatch function monitors a specified table for changes based on a filter and executes a callback function when updates occur. It is useful for real-time data synchronization in widgets. Ensure $scope is injected into the client script function. ```javascript spUtil.recordWatch($scope, "live_profile", "sys_id=" + liveProfileId); ``` ```javascript 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); }); } ``` ```javascript 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); } }); ``` -------------------------------- ### Pass Approval Count to Agent Chat URL Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Appends `sysparm_approval_count` to the Agent Chat iframe URL when a conversation is initiated from the Service Portal homepage. This context is managed using `spContextManager`. No external dependencies are explicitly mentioned. ```javascript function ($scope, spContextManager) { spContextManager.getContextForKey('agent-chat', true).then(function(context) { context = context || {}; context.approval_count = 5; spContextManager.updateContextForKey('agent-chat', context); }); } ``` -------------------------------- ### Refresh Widget Data and Options - JavaScript Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The refresh function calls the server to update the current widget's options and data based on the server's response. It is analogous to server.refresh() but allows for specifying the $scope object. ```javascript spUtil.refresh($scope); ``` -------------------------------- ### Update Context Data with spContextManager (JavaScript) Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The spContextManager.updateContextForKey() method sends updated data to an existing key. This is essential when another widget has already initialized the key, such as 'agent-chat', and you need to modify its data rather than creating a new entry. It requires the key name and the new context object. ```javascript function($scope, spContextManager) { // Assuming 'agent-chat' key is already initialized spContextManager.updateContextForKey('agent-chat', { 'new_data': 'some_value' }); }; ``` -------------------------------- ### setBreadCrumb Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index Updates the header breadcrumbs with a provided array of breadcrumb objects. ```APIDOC ## setBreadCrumb(Object $scope, Array breadcrumbs) ### Description Updates the header breadcrumbs. ### Parameters * **$scope** (Object) - The scope object for the widget. * **breadcrumbs** (Array) - An array of objects representing the breadcrumbs to set. ``` -------------------------------- ### Update Server Data within Scope - JavaScript Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The update function sends data changes back to the server within a specified scope, similar to server.update(). It ensures that modifications made in the client are reflected on the server. ```javascript spUtil.update($scope); ``` -------------------------------- ### Update Header Breadcrumbs - JavaScript Source: https://vistaglow.com/servicenow-developer-docs-service-portal-client/index The setBreadCrumb function updates the breadcrumb navigation displayed in the widget header. It accepts a $scope object and an array representing the breadcrumb structure. ```javascript spUtil.setBreadCrumb($scope, breadcrumbs); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.