Development

What is Client Script in ServiceNow?

A client script is JavaScript that runs in the user’s browser on a form or list. It reacts to what a user does, such as changing a field, so the form can validate input or update other fields instantly.

Types of client script

onLoad scripts run when a form opens. onChange scripts run when a specific field changes, which is the most common type. onSubmit scripts run when the user saves and can stop the save by returning false. onCellEdit scripts run when a value is edited directly in a list.

The g_form API

Client scripts mainly use g_form to work with the form: g_form.setValue(), g_form.setMandatory(), g_form.setDisplay(), g_form.showFieldMsg() and g_form.addErrorMessage(). g_user gives information about the logged-in user, such as their roles.

A practical example

An onChange script on the Category field of an incident clears the Subcategory and shows a message when the category changes to “Network,” reminding the user to fill in the affected location.

Getting data from the server

Client scripts should not use GlideRecord to query the database, because it is slow and blocks the browser. Instead, use GlideAjax to call a client-callable script include, or a display business rule that preloads values into g_scratchpad.

Best practices

Use a UI policy instead when you only need to make fields mandatory, read-only or hidden; UI policies need no code. Keep onLoad scripts light, since they affect every form load. Test on both the classic UI and workspaces, because some g_form methods behave differently there.

Frequently asked questions

Do client scripts replace server validation?

No. Client scripts only run on forms, so imports, APIs and integrations bypass them. Use business rules or data policies for rules that must always apply.

Should I use a client script or a UI policy?

Use a UI policy for simple show, hide, mandatory or read-only behavior. Use a client script for anything that needs logic or messages.

Why is GlideRecord on the client discouraged?

It makes synchronous calls that freeze the browser. GlideAjax is asynchronous and returns only the data you need.

sequal-consultancy-DSC02092
Take your ServiceNow to the next level

Need help with Client Script or anything else in ServiceNow? We’re here with practical solutions that fit your organization and your teams.

Get in touch

Browse all 100 ServiceNow terms

ServiceNow is a trademark of ServiceNow, Inc. This glossary is an independent resource by Sequal Consultancy and is not affiliated with or endorsed by ServiceNow, Inc.