Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Scripting

Script Includes, UI Actions and Scheduled Jobs

Organize ServiceNow server code with Script Includes, add buttons and links with UI Actions, and run recurring work with scheduled script executions and events.

Once you write more than a few scripts, you notice repeated logic. ServiceNow's answer is the Script Include: a named, reusable piece of server code. This lesson covers Script Includes, then two other places where scripts commonly live: UI Actions (buttons, links and context menu items) and Scheduled Script Executions (recurring jobs).

All ServiceNow code in this lesson is read-only and runs on an instance. The runnable blocks are labelled JavaScript stand-ins that model the structure.

Script Includes

Open System Definition > Script Includes and click New. You give it a Name, an API name (must match the class name), an Accessible from setting (This application scope only, or All application scopes) and a Client callable checkbox.

The modern pattern is a class built with Class.create() and a prototype:

JavaScript
var IncidentHelper = Class.create();
IncidentHelper.prototype = {
  initialize: function () {},

  countOpenForGroup: function (groupSysId) {
    var ga = new GlideAggregate('incident');
    ga.addActiveQuery();
    ga.addQuery('assignment_group', groupSysId);
    ga.addAggregate('COUNT');
    ga.query();
    return ga.next() ? parseInt(ga.getAggregate('COUNT'), 10) : 0;
  },

  type: 'IncidentHelper'
};

You call it from any server script:

JavaScript
var helper = new IncidentHelper();
gs.info('Open: ' + helper.countOpenForGroup(current.assignment_group));

Benefits: one copy of the logic, easier testing, and business rules that stay short. A business rule that grows beyond about twenty lines is a signal to move code here.

Client-callable Script Includes

To serve GlideAjax from forms, check Client callable and extend AbstractAjaxProcessor:

JavaScript
var UserLookupAjax = Class.create();
UserLookupAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {
  getDepartment: function () {
    var user = new GlideRecord('sys_user');
    if (user.get(this.getParameter('sysparm_user'))) {
      return user.getDisplayValue('department');
    }
    return '';
  },
  type: 'UserLookupAjax'
});

Security note: client-callable code is reachable by anyone who can reach the instance with a session. Check roles inside the method (gs.hasRole('itil')) and never return data the caller should not see.

Utility Script Includes (not a class)

A Script Include with a single function whose name equals the record name is callable like a global function. Prefer classes: they namespace your code and support several methods.

UI Actions

A UI Action adds a button, link or menu item. Table: System Definition > UI Actions (or Related Lists > UI Actions on a table). Key fields:

  • Table, Action name (used by scripts to identify it), Order.
  • Form button, Form link, Form context menu, List banner button, List choice and similar checkboxes control where it appears.
  • Condition: a server expression controlling visibility, such as current.active == true && gs.hasRole('itil').
  • Client checkbox: run the Onclick function in the browser first, then the server script if you call gsftSubmit().
  • Script: the server code.
JavaScript
// UI Action "Resolve with note" (server side)
current.state = 6;
current.close_code = 'Solved (Permanently)';
current.close_notes = 'Resolved from UI action.';
current.update();
action.setRedirectURL(current);

In a UI Action it is correct to call current.update(), because there is no automatic save as in a before rule. action.setRedirectURL(current) returns the user to the record.

Use the Condition field to hide actions from people who should not see them, and also protect the work behind it (ACLs, role checks), since the button being hidden is not security.

Scheduled Script Executions

A Scheduled Script Execution (System Definition > Scheduled Jobs) runs code on a schedule: daily, weekly, monthly, periodically or on demand. Typical jobs: closing resolved incidents after five days, expiring old records, sending a digest. In current releases the same result is often built as a flow with a schedule trigger, which is easier to read. Keep jobs for cases needing a script.

JavaScript
// Close incidents resolved more than 5 days ago
var gr = new GlideRecord('incident');
gr.addQuery('state', 6);
gr.addQuery('resolved_at', '<', gs.daysAgo(5));
gr.setLimit(500);
gr.query();
while (gr.next()) {
  gr.state = 7;
  gr.update();
}

Always limit, always run it at a quiet time, and log what you did.

Events

An event is a named signal, recorded in the event queue (sysevent). A rule queues one with gs.eventQueue('my.event', current, parm1, parm2). Script Actions and Notifications subscribe to it. Events decouple "what happened" from "what to do about it".

Modeling a Script Include

The stand-in below mimics a class with a utility method and a ClientAjax-style dispatcher. It is JavaScript for practice, not platform code.

JS Stand-in: a reusable helper class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The next stand-in models the part of GlideAjax that people forget: the method receives parameters by name and must check who is asking.

JS Stand-in: a client-callable method that checks the caller

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must the Script Include's name match when you use the class pattern?

    The API name and the class created with Class.create must be identical for the platform to find it.
  2. 2. What must you check on a Script Include used by GlideAjax?

    Client callable exposes it to GlideAjax calls, which is why you must also check roles inside.
  3. 3. In a UI Action server script, is current.update() appropriate?

    A UI Action runs after the form is submitted, so changes need an explicit update.
  4. 4. What is an event used for?

    Events decouple the thing that happened from the reactions to it.

Summary

  • Script Includes hold reusable server code; client-callable ones power GlideAjax and must check access.
  • UI Actions add buttons and links, with conditions and server or client scripts.
  • Scheduled jobs and events run work on a timer or in response to named signals.
  • Prefer flows for readable automation and keep scripts short by calling Script Includes.

Next: Consuming and Exposing REST APIs