0% found this document useful (0 votes)
4 views33 pages

ServiceNow Complete Client API Summary - MD

The document is a complete reference for the ServiceNow Client-Side API, detailing various APIs such as GlideForm, GlideList2, GlideModal, and more. It includes methods, parameters, return types, and purposes for each API, providing a comprehensive guide for developers. The structure is organized into sections covering form manipulation, notifications, user information, and more, facilitating easy navigation and understanding of the API functionalities.

Uploaded by

garvit.kumbhat18
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views33 pages

ServiceNow Complete Client API Summary - MD

The document is a complete reference for the ServiceNow Client-Side API, detailing various APIs such as GlideForm, GlideList2, GlideModal, and more. It includes methods, parameters, return types, and purposes for each API, providing a comprehensive guide for developers. The structure is organized into sections covering form manipulation, notifications, user information, and more, facilitating easy navigation and understanding of the API functionalities.

Uploaded by

garvit.kumbhat18
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ServiceNow Client-Side API Complete Reference

Table of Contents
1. GlideForm (g_form)
2. GlideList2 (g_list)
3. GlideModal
4. GlideModalForm
5. GlideRecord (Client-Side)
6. GlideUser (g_user)
7. GlideAjax
8. GlideNotification (g_notification)
9. GlideNavigation (g_navigation)
10. GlideMenu (g_menu, g_item)
11. GlideGuid (g_guid)
12. GlideURLV3
13. GlideUIScripts (g_ui_scripts)
14. Guided Tours API
15. NotifyClient
16. i18N (g_i18n)
17. Mobile GlideForm (g_form)
18. g_service_catalog
19. SNAnalytics
20. spContextManager
21. spModal
22. spUtil
23. StandaloneClientMethods
24. ScopedSessionDomain
25. ScriptLoader
26. spAriaUtil
27. StopWatch
28. GlideFlow
29. GlideAjax (Enhanced Reference)
30. GlideAgentWorkspace (g_aw)
31. DynamicTranslation
32. GlideDocument (g_document)
33. NotifyOnTaskClient (To be researched)
34. openFrameAPI (To be researched)

1. GLIDEFORM (g_form) API


Form Value Retrieval & Manipulation
Method Parameters Returns Purpose

getValue() fieldName String Get field value

getDisplayValue() fieldName String Get display value (Service


Portal)

getDisplayBox() fieldName HTMLElement Get display value (Core UI)

getDecimalValue() fieldName String Get decimal value

getIntValue() fieldName Number Get integer value

getBooleanValue() fieldName Boolean Get boolean value

setValue() fieldName, value void Set field value

setValue() fieldName, value, void Set reference field with


displayValue display value

clearValue() fieldName void Clear field value

Field Properties & State


Method Parameters Returns Purpose

isVisible() fieldName Boolean Check if field is visible

isMandatory() fieldName Boolean Check if field is mandatory

isNewRecord() - Boolean Check if record is new (unsaved)

setVisible() fieldName, display void Show/hide field

setDisplay() fieldName, display void Display/hide field


Method Parameters Returns Purpose

setMandatory() fieldName, mandatory void Make field mandatory/optional

setReadOnly() fieldName, readOnly void Make field read-only/editable

setDisabled() fieldName, disable void Enable/disable field

Choice List & Options


Method Parameters Returns Purpose

addOption() fieldName, value, label void Add choice to list end

addOption() fieldName, value, label, void Add choice at specific


index position

removeOption() fieldName, value void Remove choice from list

clearOptions() fieldName void Clear all choices

getOption() fieldName, value HTMLElement Get option element

getChoice() fieldName, value GlideFormChoice Get choice object

getOptions() fieldName Array Get all available options

disableChoice() fieldName, value Boolean Disable specific choice

enableChoice() fieldName, value Boolean Enable specific choice

setChoiceLabel() fieldName, value, Boolean Update choice label


newLabel

Field Labels & Decorations


Method Parameters Returns Purpose

getLabelOf() fieldName String Get field label text

setLabelOf() fieldName, label void Set field label text

addDecoration() fieldName, icon, title void Add icon to field label


Method Parameters Returns Purpose

addDecoration() fieldName, icon, title, color void Add colored icon

removeDecoration() fieldName, icon, title void Remove icon

removeDecoration() fieldName, icon, title, color void Remove colored icon

Messages & Notifications


Method Parameters Returns Purpose

addErrorMessage() message void Display error (4 sec)

addInfoMessage() message void Display info (4 sec)

addSuccessMessage() message void Display success (4 sec)

addHighMessage() message void High priority (4 sec)

addModerateMessage() message void Moderate priority (4 sec)

addLowMessage() message void Low priority (4 sec)

clearMessages() - void Clear all messages

addFormMessage() message, type, options void Floating message with buttons

clearFormMessages() type void Clear by type

clearAllFormMessages() - void Clear all form messages

Field-Level Messages
Method Parameters Returns Purpose

showErrorBox() fieldName, message void Show error under field

showErrorBox() fieldName, message, void With scroll option


scrollForm

hideErrorBox() fieldName void Hide error under field


Method Parameters Returns Purpose

showFieldMsg() field, message, type void Show message under


field

showFieldMsg() field, message, type, scrollForm void With scroll option

hideFieldMsg() fieldName, clearAll void Hide field message

hideAllFieldMsgs() - void Hide all messages

hideAllFieldMsgs() type void Hide by type

Sections & Layout


Method Parameters Returns Purpose

getSectionNames() - Array Get all section names

getSections() - Array Get all section elements

setSectionDisplay() sectionName, display Boolean Show/hide section

isSectionVisible() sectionName Boolean Check visibility

Related Lists & Links


Method Parameters Returns Purpose

getRelatedListNames() - Array Get related list names

showRelatedList() listTableName void Display specific list

hideRelatedList() listTableName void Hide specific list

showRelatedLists() - void Display all lists

hideRelatedLists() - void Hide all lists

showRelatedLinks() - void Display links section

hideRelatedLinks() - void Hide links section

setRelatedLinksDisplay() display void Toggle links


Annotations
Method Parameters Returns Purpose

getAnnotations() - Array Get all annotations

getAnnotationByName() name Array Get by name

showAnnotation() name void Show annotation

hideAnnotation() name void Hide annotation

toggleAnnotations() - void Toggle all

Form Metadata
Method Parameters Returns Purpose

getTableName() - String Get table name

getUniqueValue() - String Get record sys_id

getActionName() - String Get action name/sys_id

getReference() fieldName, callback GlideRecord Get reference record

Form Controls & Elements


Method Parameters Returns Purpose

getControl() fieldName HTMLElement Get field element

getElement() id HTMLElement Get by ID

getFormElement() - HTMLFormElement Get form element

getHelpTextControl() fieldName HTMLElement Get help text


Attachments & Files
Method Parameters Returns Purpose

enableAttachments() - void Allow attachments

disableAttachments() - void Prevent attachments

Form Actions & Submission


Method Parameters Returns Purpose

save() - void Save without navigate

submit() - void Save and navigate

submit() verb void Perform UI action

Visual Effects & Templates


Method Parameters Returns Purpose

flash() fieldName, color, count void Flash field

showTemplateBar() - void Show template bar

hideTemplateBar() - void Hide template bar

Service Catalog & Variables


Method Parameters Returns Purpose

setVariablesReadOnly() isReadOnly void Make read-only

refreshSlushbucket() fieldName void Update collector


Event Listeners
Method Parameters Returns Purpose

onUserChangeValue() fn Function Register listener

State Checks
Method Parameters Returns Purpose

isLiveUpdating() - Boolean Check live update

2. GLIDELIST2 (g_list) API


Method Parameters Returns Purpose

addFilter() filter void Add query filter

get() DOMelement/ListID Object Get list object

getChecked() - String Get checked sys_ids

getFixedQuery() - String Get fixed query

getGroupBy() - String Get group fields

getListName() - String Get list name

getOrderBy() - String Get order field

getParentTable() - String Get parent table

getQuery() flags (4 Boolean) String Get encoded query

getRelated() - String Get related field

getTableName() - String Get table name

getTitle() - String Get list title

getView() - String Get view name


Method Parameters Returns Purpose

isUserList() - Boolean Check if personalized

refresh() firstRow, params void Refresh list

refreshWithOrderBy() firstRow, description void Refresh with order

setFilter() filter void Set filter

setFilterAndRefresh() filter void Set and refresh

setFirstRow() rowNum void Set first row

setGroupBy() groupBy void Set group field

setOrderBy() orderBy void Set order field

setRowsPerPage() rows void Set rows per page

showHideGroups() showFlag void Show/hide groups

showHideList() showFlag void Show/hide list

sort() field void Sort ascending

sortDescending() field, amount void Sort descending

toggleList() - void Toggle display

toggleListNoPref() - void Toggle without pref

3. GLIDEMODAL API
Method Parameters Returns Purpose

GlideModal() id, readOnly, width - Constructor

destroy() - void Close modal

get() id GlideModal Get modal by ID

getPreference() name String Get preference


Method Parameters Returns Purpose

render() - void Render modal

renderWithContent() html void Render with HTML

setPreference() name, value void Set preference

setPreferenceAndReload() properties void Set and reload

setTitle() title void Set title

setWidth() width void Set width

switchView() newView void Change view

updateTitle() - void Update title

Modal Width Classes:


modal-alert : 300px (0-349px range)
modal-sm : 400px (350-449px range)

modal-md : 600px (450-649px range) - default


modal-lg : 900px (650-900px range)

4. GLIDEMODAL FORM API


Method Parameters Returns Purpose

GlideModalForm() title, table, callback, - Constructor


readOnly

addParm() name, value void Set field value

render() - void Show modal form

setCompletionCallback() callbackFunction void Set completion


callback

setOnloadCallback() callbackFunction void Set onload callback

setSysID() sys_id void Set sys_id


Callback signature:

javascript

function callback(action_verb, sys_id, table, displayValue) { }

5. GLIDERECORD (CLIENT-SIDE) API


Method Parameters Returns Purpose

GlideRecord() tableName - Constructor

addOrderBy() column void Add order column

addQuery() name, operator, value void Add filter condition

addQuery() name, value void Add equality filter

deleteRecord() responseFunction void Delete record

get() sys_id Boolean Get by sys_id

getEncodedQuery() - String Get query string

getLimit() - Number Get record limit

getTableName() - String Get table name

hasNext() - Boolean Check for more

insert() responseFunction String Insert record

next() - Boolean Move to next

orderBy() column void Specify order

query() name, function, value void Execute query

setEncodedQuery() encodedQuery void Set complex filter

setLimit() maxQuery void Set limit

Query Operators:
Numbers: = , != , > , >= , < , <=

Strings: = , != , IN , NOT IN , STARTSWITH , ENDSWITH , CONTAINS , DOES NOT CONTAIN ,


INSTANCEOF

6. GLIDEUSER (g_user) API


Properties
Property Type Description

firstName String Current user's first name

lastName String Current user's last name

userID String User sys_id

userName String User's username

Methods
Method Parameters Returns Purpose

getClientData() key String Get client data

getFullName() - String Get full name

hasRole() role, includeDefaults Boolean Check role

hasRoleExactly() role, includeDefaults Boolean Check exact role

hasRoleFromList() roles, includeDefaults Boolean Check role list

hasRoles() includeDefaults Boolean Check any role

setClientData() key, value void Set client data


7. GLIDEAJAX API
Method Parameters Returns Purpose

GlideAjax() scriptIncludeOrClassName - Constructor

addParam() name, value void Add parameter

getXML() callback void Async request

getXMLAnswer() callback, param1, param2 void Async with params

getXMLWait() - void Sync request

getAnswer() - String Get answer (after wait)

Response object properties:


[Link] : HTTP status code
[Link] : Status text
[Link] : Parsed XML

[Link] : Raw XML text

8. GLIDENOTIFICATION (g_notification) API


Method Parameters Returns Purpose

show() type, message, duration void Display notification

Message types: error , info , warning Duration: milliseconds (default: 5000)

9. GLIDENAVIGATION (g_navigation) API


Method Parameters Returns Purpose

open() url, target void Redirect to URL

openPopup() url, name, features, noStack Window Open popup


Method Parameters Returns Purpose

openRecord() tableName, sys_id void Open record

refreshNavigator() - void Refresh navigator

reloadWindow() - void Reload frame

10. GLIDEMENU (g_menu, g_item) API


Method Parameters Returns Purpose

clearImage() item void Remove image

clearSelected() - void Clear selection

getItem() itemID GlideMenuItem Get item by ID

setDisabled() item void Disable item

setEnabled() item void Enable item

setHidden() item void Hide item

setImage() item, imgSrc void Set image

setLabel() item, label void Set label

setVisible() item void Show item

11. GLIDEGUID (g_guid) API


Method Parameters Returns Purpose

generate() stringLength String Generate GUID

stringLength: 1-32 (default: 32)


12. GLIDEURLV3 API
Method Parameters Returns Purpose

GlideURL() contextPath - Constructor

addParam() name, value GlideURL Add param

getURL() additionalParams String Get full URL

13. GLIDEUISCRIPTS (g_ui_scripts) API


Method Parameters Returns Purpose

getUIScript() scriptName Promise Load UI script

14. GUIDED TOURS API


Method Parameters Returns Purpose

applyListFilter() filter_func void Filter tours

endTour() - void Stop tour

[Link]() event_name, listener void Remove listener

[Link]() event_name, listener void Add listener

getAllTours() cb_function void Get all tours

loadPlayer() - void Load player

startTour() tour_id, step, callback void Start tour

Access pattern: [Link].guided_tours.[Link]()

Events: tourStarted , tourEnded , tourCompleted , tourFailed , tourAbandoned ,


tourDismissed , stepStarted
15. NOTIFYCLIENT API
Method Parameters Returns Purpose

Client() notifyConfig, initLazy - Constructor

addEventListener() event, fn Function Register listener

call() identifier void Make/receive call

destroy() - void Kill client

forwardCall() argument void Forward call

getAvailableClients() callback void Get clients list

getParentId() callId, callback String Get parent ID

getStatus() - String Get call status

hangupCall() - void End call

init() - void Initialize

mute() muted void Mute/unmute

pickupCall() - void Answer call

sendDtmf() digits void Send DTMF

setCallerId() value, callback void Set caller ID

setClientAvailable() available void Set availability

16. i18N (g_i18n) API


Method Parameters Returns Purpose

format() message, map String Format with tokens

getMessage() msgKey, callback void Get translated message


Method Parameters Returns Purpose

getMessages() msgKeys, callback void Get multiple messages

17. MOBILE GLIDEFORM (g_form) API


Method Parameters Returns Purpose

addDecoration() fieldName, icon, text void Add icon

getLabel() fieldName String Get label

hasField() fieldName Boolean Check field exists

removeDecoration() fieldName, icon, text void Remove icon

setLabel() fieldName, label void Set label

18. g_service_catalog API


Method Parameters Returns Purpose

getValue() variableName String Get parent form value

Access pattern: g_service_catalog.[Link]()

19. SNANALYTICS API


Purpose: Push custom analytics data to Usage Insights for Service Portal dashboard
Requires: Service Portal Analytics plugin ([Link]) activated
Import: snAnalytics AngularJS service in widget client script
Method Parameters Returns Purpose

addEvent() payload (Object) void Store event in analytics

appendToUserProperty() name (String|Array), void Append to string property


value (String)

incUserProperty() name (String), value void Increment/decrement


(Number) property

removeUserProperty() name (String) void Remove user property

setUserProperties() properties (Object) void Set multiple properties

setUserProperty() name (String), value void Set single property


(UserProperty)

startPage() name (String), description void Track page visit


(String)

Property Types: String, Boolean, Number, Date, String[], Null


Event Payload Structure:

javascript

{
name: "Event Name",
data: {
"Property1": value,
"Property2": value
}
}

20. SPCONTEXTMANAGER API


Purpose: Share widget data with other applications (Agent Chat, etc.) Context: AngularJS
service for Service Portal widgets Keys: agent-chat (sends data to Agent Chat)
Method Parameters Returns Purpose

addContext() key (String), context (Object) void Initialize key with


data

getContext() - Object Get all keys and


data

getContextForKey() key (String), returnPromise Promise|Object Get data for key


(Boolean)

updateContextForKey() key (String), context (Object) void Update existing


key

21. SPMODAL API


Purpose: Display alerts, prompts, and confirmation dialogs in Service Portal widgets
Context: Service Portal client scripts

Method Parameters Returns Purpose

alert() message (String) Promise<Boolean> Show alert dialog

confirm() message (String) Promise<Boolean> Show confirmation

open() options (Object) Promise Open modal with


options

prompt() message (String), default Promise<String> Show input prompt


(String)

Modal Options:
backdrop : Boolean|"static" - Controls backdrop
buttons : Array - Custom buttons {label, cancel, primary}

input : Boolean - Show input field


keyboard : Boolean - Allow ESC to close

message : String - HTML header content


noDismiss : Boolean - Hide close icon
shared : Object - Share data with widget
size : "sm"|"lg" - Modal size
title : String - Modal title
value : String - Input field default

widget : String - Widget ID to embed


widgetInput : Object - Data for widget

22. SPUTIL API


Purpose: Utility methods for Service Portal widget client scripts
Method Parameters Returns Purpose

addErrorMessage() message (String) void Show error notification

addInfoMessage() message (String) void Show info notification

addTrivialMessage() message (String) void Show trivial notification

createUid() - String Generate unique 32-char


ID

format() template (String), data (Object) String Format string with vars

get() widgetId (String), data (Object) Object Embed widget model

getHeaders() - Object Get API headers

getHost() - String Get host domain

getPreference() preference (String), callback void Get user preference


(Function)

getURL() - String Get portal URL info

isMobile() - Boolean Check if mobile device

parseAttributes() attributes (String) Array Parse comma-separated


attrs

recordWatch() $scope, table, filter, callback Promise Watch table updates

refresh() $scope (Object) Object Refresh from server

scrollTo() selector (String), time void Scroll to element


(Number)

setBreadCrumb() $scope, breadcrumbs (Array) void Update breadcrumbs

setPreference() pref (String), value (String) void Set user preference

setSearchPage() searchPage (String) void Update search page

update() $scope (Object) Object Update data on server


Purpose: Client methods accessible without class instantiation

Method Parameters Returns Purpose

reflistOpen() target, elementName, refTableName, Pop-up Open


dependent, useQBE, refQualElements, Window reference
additionalQual, parentID, forceReference, field popup
ignoreTargetValue

reflistOpen Parameters:
target : Form target field (e.g., "incident.caller_id")
elementName : Field name (e.g., "caller_id")
refTableName : Reference table (e.g., "sys_user")

dependent : Dependent field


useQBE : "true"/"false" - Show query form

refQualElements : Reference qualifiers


additionalQual : Additional filter query
parentID : Internal parameter

forceReference : Internal parameter


ignoreTargetValue : Internal parameter

24. SCOPEDSESSIONDOMAIN API


Purpose: Access session domain information Requirements: Domain Support plugin
([Link].msp_extensions) + admin role Access: Via GlideAjax for client scripts

Method Parameters Returns Purpose

getCurrentDomainID() - String Get current domain sys_id

Return Values:
null : User in global domain (no domain picker used)
"global" : User switched to global domain

sys_id : Domain identifier


Client Script Usage:

javascript

var ga = new GlideAjax("[Link]");


[Link]("sysparm_name", "getCurrentDomainID");
[Link](callback);

25. SCRIPTLOADER API


Purpose: Load scripts asynchronously Availability: ListV2/ListV3 (NOT Service
Portal/Mobile/Agent Workspace) Access: Global ScriptLoader object

Method Parameters Returns Purpose

getScripts() scripts (Array), callback (Function) void Load array of scripts

getScripts() filePath (String), callback (Function) void Load single script file

Usage:

javascript

[Link]([
'scripts/[Link]',
'scripts/[Link]'
], function() {
// Code runs after scripts loaded
});

26. SPARIAUTIL API


Purpose: Send messages to screen readers (accessibility) Context: Service Portal widget
client scripts Access: Angular service spAriaUtil

Method Parameters Returns Purpose

sendLiveMessage() message (String) void Announce to screen reader


Note: Default aria-live region is assertive (immediate announcement)

27. STOPWATCH API


Purpose: Measure operation duration Availability: ListV2/ListV3 APIs Usage: Detect
performance issues

Method Parameters Returns Purpose

StopWatch() - Object Constructor (start timer)

StopWatch() initialDate (Date) Object Constructor with start date

getTime() - Number Get elapsed ms

restart() - void Reset timer

toString() - String Get elapsed time HH:MM:[Link]

Example Usage:

javascript

var sw = new StopWatch();


// ... code to measure
if ([Link]() > 500) {
[Link]("Slow operation: " + [Link]());
}
[Link]();
// ... more code
[Link]();

28. GLIDEFLOW API


Purpose: Client-side interactions with actions, flows, and subflows Requirements: Client
callable flows/actions with valid ACL Incompatible: Workspace Experience UI Returns:
Promise objects
Method Parameters Returns Purpose

[Link]() - Object Wait for


completion

[Link]() - String Get execution


status

[Link]() - Object Get outputs

getExecution() executionId (String) Promise Get existing


execution

startAction() scopedName (String), Promise Start action


inputs (Object)

startFlow() scopedName (String), Promise Start flow


inputs (Object)

startSubflow() scopedName (String), Promise Start subflow


inputs (Object)

Execution Status: String (e.g., "COMPLETE")


Example Usage:

javascript

[Link]('global.action_name', {input1: 'value'})


.then(function(execution) {
return [Link]();
})
.then(function(completion) {
[Link]([Link]);
[Link]([Link]);
});

29. GLIDEAJAX API (Enhanced Reference)


Purpose: Call server-side code from client scripts Access: Via Script Includes extending
AbstractAjaxProcessor
Method Parameters Returns Purpose

GlideAjax() class_name (String) - Constructor

addParam() parm_name (String), parm_value void Add parameter


(String)

getXML() callback (Function) void Async request (preferred)

getXMLAnswer() callback, additionalParam, void Async with extra params


responseParam

getXMLWait() - void Sync request (NOT


recommended)

getAnswer() - void Get answer after wait

First param always: sysparm_name with method name


Callback signature:

javascript

function callback(response) {
var answer = [Link]("answer");
}

30. GLIDEAGENTWORKSPACE (g_aw) API


Purpose: Agent Workspace tab and record management Access: g_aw global object
Availability: Agent Workspace client scripts only
Method Parameters Returns Purpose

closeRecord() - Promise Close current


record

domainScopeProvider() - Object Get domain scope


details

openRecord() table (String), sysId (String), Promise Open record in


params (Object) subtab

setSectionExpanded() section_name (String), expanded void Set section state


(Boolean)

openRecord() Params:
readOnlyForm : Boolean - All fields read-only
defaultTab : String - Initial tab name
hideDetails : Boolean - Hide details tab

domainScopeProvider() Functions:
getDomainScope() : Returns scope (SESSION/RECORD)
hasDomainChanged() : Check if domain changed
isDomainEnabledRecord() : Check if domain-enabled

toggleDomainScope() : Toggle scope mode

31. DYNAMICTRANSLATION API


Purpose: Real-time text translation using service providers Requirements: Dynamic
Translation plugin activated Service Portal: Use dynamicTranslation (not
DynamicTranslation ) Providers: Microsoft Azure, Google Cloud, IBM, Custom
Method Parameters Returns Purpose

getDetectedLanguage() text (String), parms (Object) Promise Detect language

getDetectedLanguages() texts (Array), parms (Object) Promise Detect multiple

getTranslation() textToTranslate (String), parms Promise Translate text


(Object)

getTranslations() texts (Array), parms (Object) Promise Translate


multiple

isEnabled() translator (String) Promise Check if enabled

Parameters Object (parms):

javascript

{
translator: "Microsoft", // Google, Microsoft, IBM, custom
sourceLanguage: "en", // Auto-detect if not specified
targetLanguages: ["fr", "it"],
additionalParameters: [{
parameterName: "texttype",
parameterValue: "plain" // or "html"
}]
}

Return Structure:

javascript

{
translator: "String",
detectedLanguage: { code: "en", name: "en", confidence: "1" },
translations: [
{ targetLanguage: "fr", translatedText: "..." }
]
}

Error Codes:
40000: Text missing/invalid
40001: Plugin not installed
40003: Translator invalid
40004: Translator not configured
40005: Translator inactive
40052: Text exceeds max length
40055: Invalid credentials

32. GLIDEDOCUMENT API


Purpose: Search and access DOM elements Availability: ListV2/ListV3 APIs Access:
g_document global object

Method Parameters Returns Purpose

getElement() selector (String), context (Element) node Get single element

getElements() selector (String), context (Element) node list Get multiple elements

Selector: CSS selector or jQuery selector Context: Optional DOM Element, document, or
jQuery object

QUICK REFERENCE BY USE CASE


Get/Set Form Values
g_form.getValue() / g_form.setValue()
g_form.getDisplayValue() / g_form.getDisplayBox()

g_form.getIntValue() / g_form.getDecimalValue() / g_form.getBooleanValue()

Field Visibility & State


g_form.setVisible() / g_form.setDisplay() / g_form.isVisible()
g_form.setReadOnly() / g_form.setMandatory() / g_form.setDisabled()

User Feedback
g_form.addErrorMessage() / g_form.addInfoMessage() / g_form.addSuccessMessage()

g_form.showFieldMsg() / g_form.showErrorBox()
g_form.addFormMessage() with buttons

Choices & Options


g_form.addOption() / g_form.removeOption() / g_form.getOptions()

g_form.enableChoice() / g_form.disableChoice()

Lists
g_list.setFilter() / g_list.setFilterAndRefresh()
g_list.sort() / g_list.sortDescending()

g_list.refresh() / g_list.refreshWithOrderBy()

Server Communication
GlideAjax() with getXML() (async, preferred)
GlideAjax() with getXMLWait() (sync, avoid)

GlideRecord with query() callback

Modals & Dialogs


GlideModal() for UI pages
GlideModalForm() for forms
GlideModal().renderWithContent() for HTML
[Link]() / [Link]() / [Link]() (Service Portal)
[Link]() (Service Portal with options)

Service Portal Widgets


[Link]() / [Link]() (notifications)
[Link]() (embed widget)
[Link]() (watch table updates)
[Link]() / [Link]() (server sync)
spModal.* (modal dialogs)
spContextManager.* (share data)

Analytics & Tracking


[Link]() (track user actions)
[Link]() (track page visits)
[Link]() (user properties)
[Link]() (increment counter)

Reference Data
g_form.getReference() - Get related record
g_form.setValue() with display value
reflistOpen() - Open reference popup

Navigation
g_navigation.open() - Redirect
g_navigation.openRecord() - Open record
g_navigation.openPopup() - Popup window

User Info
g_user.userName / g_user.userID
g_user.hasRole() / g_user.hasRoles()

g_user.getFullName()

Notifications
g_notification.show() - Toast message
Form messages - Top of form (4 sec auto-hide)
Field messages - Under field
[Link]() / [Link]() (Service Portal)

Performance & Debugging


StopWatch() - Measure operation duration
[Link]() - Generate unique ID

[Link]() - Format strings

Accessibility
[Link]() - Screen reader announcement
Script Loading
[Link]() - Load async scripts

Domain Information
[Link]() - Get domain sys_id (via GlideAjax)
g_aw.domainScopeProvider() - Agent Workspace domain scope

Workflows & Automation


[Link]() / startFlow() / startSubflow() - Trigger flows
[Link]() - Wait for completion
[Link]() - Get flow outputs

Agent Workspace
g_aw.openRecord() - Open record in subtab
g_aw.closeRecord() - Close current record
g_aw.setSectionExpanded() - Toggle section state

Translation
[Link]() - Translate text
[Link]() - Detect language

[Link]() - Check if enabled

DOM Operations
g_document.getElement() - Get single element
g_document.getElements() - Get element list

NOTES FOR YOUR SERVICENOW PDI


✅ Use on Client Scripts:
All g_form methods
g_list methods
GlideAjax with getXML() or getXMLAnswer()
g_user methods
g_navigation methods
GlideModal
GlideNotification

⚠️ Avoid:
[Link]() - blocks UI
Synchronous GlideRecord queries
Complex nested callbacks - use async/await patterns

📌 Best Practices:
Always use async callbacks (getXML, getXMLAnswer)
Validate user input before server calls
Use g_form methods instead of direct DOM manipulation
Check g_user.hasRole() before showing sensitive fields
Avoid multiple setValue() calls in onChange - can cause stack overflow

You might also like