Client Script in ServiceNow

Client Script in ServiceNow

A Client Script in ServiceNow is a piece of JavaScript code that runs in the user's web browser, providing dynamic control of the user interface and user interactions.

We can:

  1. Modify the choice list option
  2. set one field in response to another
  3. Hide/Show form section
  4. Display an alert
  5. Make fields mandatory
  6. Hide Fields


Types of Client Script:

Types of Client Script in ServiceNow


  1. onLoad() - Executes when a form is initially loaded.
  2. onChange() - Executes when a specified field's value changes.
  3. onSubmit() - Executes when a form is submitted.
  4. onCellEdit() - Executes when a cell value in a list is edited.


Client Script trigger:

The trigger condition must be met for the client script to execute.

Trigger conditions must be met for the client script to execute.

  • Name: The name assigned to the client script.
  • Table: The table on which the client script runs.
  • UI Type: The user interface type where the script is applied (e.g., All, Mobile, Desktop).
  • Type: The type of client script, such as onLoad, onChange, onSubmit, or onCellEdit.
  • Application: The application scope to which the client script belongs.
  • Active: A boolean value indicating whether the client script is enabled or disabled.
  • Inherited: Indicates if the script is inherited from a parent table.
  • Global: Determines if the client script is global or restricted to a specific application scope.
  • Description: A brief description of what the client script does.
  • Message: Optional field for storing additional information or messages related to the client script.
  • Script: The JavaScript code executed by the client script.
  • Isolate Script: Determines if the client script should run in an isolated scope to prevent conflicts with other scripts.


1. onLoad()

Definition:

The onLoad() Client Script executes when a form is initially loaded. It can be used to perform tasks like setting default values, hiding/showing fields, or modifying field properties.

Syntax:

Example:

Scenario 1:

Suppose you want to make the "Short Description" field mandatory when the form loads if the "Category" field is set to "Hardware."

This example demonstrates how to dynamically change the properties of a field based on the value of another field when the form loads.

2. onChange()

Definition:

The onChange() Client Script executes when a specified field's value changes. It can be used to validate field values, auto-fill related fields, or trigger other actions based on field changes.

Syntax:

control: This parameter represents the HTML element of the field that triggered the onChange event. You typically don't need to interact with this directly.

oldValue: This is the value of the field before the change occurred. It allows you to compare the old value with the new value.

newValue: This is the new value of the field after the change occurred. Your script can use this value to determine the appropriate actions to take.

isLoading: This is a boolean parameter that indicates whether the form is currently loading. It's helpful to check this parameter to avoid executing the script during the initial load of the form.

Example:

Scenario 2:

Suppose you want to set the "Assignment Group" field automatically based on the "Category" field value in an Incident form. For example, if the "Category" is set to "Network," you want to assign the incident to the "Network Support" group. If the "Category" is "Hardware," assign it to the "Hardware Support" group.


3. onSubmit()

Definition:

The onSubmit() Client Script executes when a form is submitted. It can be used to perform validation checks, show confirmation messages, or prevent form submission under certain conditions.

Syntax:

Example:

Scenario 3:

Let's say you want to prevent the form from being submitted if the "Description" field is empty.


4. onCellEdit()

Definition:

The onCellEdit() Client Script executes when a cell value in a list is edited. It can be used to perform real-time validation or updates based on the cell's new value.

Syntax:

  1. sysIds: Array of Sys IDs for the records that were edited.
  2. table: Name of the table where the cell edit occurred.
  3. oldValues: Object with the old values of the edited cells, keyed by field name.
  4. newValues: Object with the new values of the edited cells, keyed by field name.
  5. callback: Function to call when your processing is complete, ensuring the list edit is finalized.

Example:

Scenario 4:

In ITSM (IT Service Management), you want to prevent saving changes to the "Priority" field in the Incident list view if it is changed to "High" when the "State" is "Closed." This ensures that once an incident is closed, its priority cannot be modified.


Imp APIs of Client Script:

The two important APIs of client scripts in ServiceNow are "g_form" and "g_user".

1) g_form:

  • Purpose: The g_form API provides methods to interact with form fields, control form behavior, and perform client-side validation.
  • Key Methods:

  1. g_form.getValue('field_name'): Retrieves the value of a specified field.
  2. g_form.setValue('field_name', value): Sets the value of a specified field.
  3. g_form.setReadOnly('field_name', true/false): Makes a field read-only or editable.
  4. g_form.setMandatory('field_name', true/false): Makes a field mandatory or optional.
  5. g_form.setDisplay('field_name', true/false): Shows or hides a field.
  6. g_form.addErrorMessage('message'): Displays an error message on the form.
  7. g_form.addInfoMessage('message'): Displays an informational message on the form.


2) g_user:

  • Purpose: The g_user API provides methods to retrieve information about the current logged-in user.
  • Key Methods:

  1. g_user.userID: Returns the user ID of the current user.
  2. g_user.userName: Returns the username of the current user.
  3. g_user.firstName: Returns the first name of the current user.
  4. g_user.lastName: Returns the last name of the current user.
  5. g_user.hasRole('role_name'): Checks if the current user has a specified role.
  6. g_user.getFullName(): Returns the full name of the current user.
  7. g_user.hasRoles(): Checks if the current user has any roles.


Best practices for Client Script:

Here are best practices for writing client scripts in ServiceNow with brief explanations:

  • Minimize Script Execution:

Only run scripts when necessary to avoid performance issues. Use conditions to limit script execution to specific scenarios, ensuring scripts run only when required to enhance user experience and system efficiency.

  • Use g_form and g_user Efficiently:

Leverage these APIs for form manipulation and user information retrieval. Use g_form.getValue() and g_user.hasRole() judiciously to interact with form fields and user roles without redundant calls, which can degrade performance.

  • Avoid Hardcoding:

Use dynamic methods to get field values, labels, and other data to make scripts more flexible and maintainable. This approach reduces the risk of errors during updates and makes the script adaptable to changes in the form structure.

  • Error Handling:

Implement proper error handling using try-catch blocks and provide user-friendly error messages. This ensures that users receive clear feedback when something goes wrong, and prevents the script from failing silently or breaking the form.

  • Use g_scratchpad for Server-Client Communication:

Pass data from server-side scripts to client scripts using g_scratchpad to maintain a clear separation of concerns. This helps in efficiently sharing necessary data without multiple server calls, improving performance.

  • Code Reusability:

Write reusable functions and avoid duplicating code. Keeping your scripts modular and organized reduces maintenance effort and makes your codebase cleaner and easier to understand.

  • Optimize Performance:

Avoid using synchronous GlideAjax calls; prefer asynchronous calls to avoid blocking the UI. This ensures that the user interface remains responsive and improves the overall user experience.

  • Security Considerations:

Ensure that sensitive operations and data are handled on the server side to prevent security vulnerabilities. Avoid exposing sensitive logic and data to the client side, which could be manipulated by malicious users.

  • Testing and Debugging:

Use browser developer tools for testing and debugging. Test scripts thoroughly in different scenarios to ensure they work as expected and to catch and fix issues early in the development process.

  • Documentation and Comments:

Document your code with comments to explain complex logic and maintain readability for future developers. Well-documented code helps others understand your logic and makes maintenance easier.


*********************************************************************************************

"Thank you for reading. I hope you find these best practices helpful in optimizing your ServiceNow client scripts!"
Venkatesh Tadiparthi

ServiceNow Developer at NTT Data Services.

4 个月

Good work SAURABH TRIPATHI

回复
DHAIRYA MEHTA

SOFTWARE DEVELOPER | ANGULAR | JAVA | NODE | SQL

4 个月

Useful tips SAURABH TRIPATHI

回复

Great guide! Mastering client scripts in ServiceNow is crucial for efficiency. I often optimize scripts by ensuring they run only when necessary and avoiding redundant queries. How do you prioritize script performance?

回复
Kritika Sharma

ServiceNow Developer | CAD | ITSM | Flow Designer | ATF | Agile | Admin | AWS | Figma | UI/UX Designing

4 个月

Thanks for sharing SAURABH TRIPATHI ????

回复
Rangnath Bade

[ServiceNow Developer | Consultant | CSA | CAD | ITSM | HRSD | ITOM |CMDB| CSM | Portal | Mobile Application| UI Builder| Integration | Javascript | NodeJs | German-A1]

4 个月

Thanks for sharing SAURABH TRIPATHI

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了