0% found this document useful (0 votes)
18 views14 pages

Understanding Script Actions in ServiceNow

Script Actions are server-side JavaScript code that execute in response to specific events, allowing for automation and data modification within ServiceNow. They differ from Script Includes, which are reusable logic libraries, by being event-driven and capable of asynchronous execution. Script Actions are essential for handling tasks that require immediate responses to events, complementing Script Includes for more complex logic implementations.

Uploaded by

dayashankar
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)
18 views14 pages

Understanding Script Actions in ServiceNow

Script Actions are server-side JavaScript code that execute in response to specific events, allowing for automation and data modification within ServiceNow. They differ from Script Includes, which are reusable logic libraries, by being event-driven and capable of asynchronous execution. Script Actions are essential for handling tasks that require immediate responses to events, complementing Script Includes for more complex logic implementations.

Uploaded by

dayashankar
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

Sometimes, interviewers ask, “Why Script Action is needed when we already

have Script Include?” This question makes us think why? We will try to
understand this with use-case after knowing about Script Action.

Script Action
Script actions are server-side JavaScript code that is executed when an event
it is listening to is triggered on the specified table. Just like any other server-
side script, script actions have access to all the server-side glide APIs, script
includes, and other server-side resources.

In other words,

Script Actions are server-side scripts that execute in response to specific


events. They act as event handlers, allowing you to automate tasks or modify
data when certain actions occur within the system, such as record updates or
business rule executions.

Here's a more detailed explanation:

• Event-Driven:

Script Actions are triggered by events, meaning they only run when a
predefined event occurs.

• Server-Side:

They run on the server, giving them access to all server-side APIs, script
includes, and other server-side resources.

• Asynchronous Execution:

Script Actions typically run in the background (asynchronously), allowing the


user interface to remain responsive while the script executes.

SCRIPT ACTION GYANINDRA YADAV


• Customization:

They enable developers to customize ServiceNow's behavior by adding


custom logic and automation to handle specific situations.

• Examples of Use:

• Updating a field on a record after a specific business rule has run.

• Sending an email notification when a new incident is created.

• Modifying data in a related table when a specific action is


performed.

• Creating Script Actions:

You can create Script Actions within the ServiceNow Studio or by navigating to
System Policy > Script Actions in the application navigator.

• Comparison with other scripting options:

While Client Scripts work on the client-side (within the browser) and Script
Includes are reusable server-side code, Script Actions bridge the gap by
allowing you to run server-side logic in response to specific events.

Use Case-1: Create a custom reference field named Affected CI


[u_affected_ci] on the incident table. Reference it to [cmdb_ci_server] table.

While creating an incident, if user selects any Affected CI and some state then
after inserting that incident….… The Comments field of that CI record on
[cmdb_ci_server] table should be updated as per the below conditions –

A. If CI is not changed & Incident is not RESOLVED, then update the


Comments fields of that CI as –

This CI is attached to INC0010074 on 2025-06-18 23:16:26. Incident state is: In


Progress

SCRIPT ACTION GYANINDRA YADAV


B. If CI is changed and Incident is RESOLVED, then –

This CI is removed from INC0010074 on 2025-06-18 23:17:16. Incident state on


the time of removal was: In Progress

C. When Incident got RESOLVED then –

This INC0010074 is resolved on 2025-06-18 23:19:06.

Since we can achieve scenario using the Business Rule also but here, we will
be using SCRIPT ACTION.

First create a field named Affected CI on Incident table.

Then, create an event. (Say update.cmdb_ci_server.comments)

Now create a Business Rule on Incident Table (Name: Update affected CI


comments) and add filter conditions.

SCRIPT ACTION GYANINDRA YADAV


In Script section, get all the value like previousCI, currentCI, changeCIFlag and
pass it to the [Link]() with current record object.

Script:

(function executeRule(current, previous /*null when async*/ ) {

// Add your code here

var previousCI = previous.u_affected_ci;

var currentCI = current.u_affected_ci;

var changeCIFlag;

if (previousCI == currentCI) {

changeCIFlag = 'false';

} else {

changeCIFlag = 'true';

[Link]('update.cmdb_ci_server.comments', current, changeCIFlag,


previousCI);

SCRIPT ACTION GYANINDRA YADAV


})(current, previous);

Save the Business Rule.

Now, Create the Script Action and select that event.

The Script:

var changeCIFlag = event.parm1;

var prevCISysID = event.parm2;

var currentCISysID = current.u_affected_ci;

var incNumber = [Link];

updateCIComment(changeCIFlag, prevCISysID);

function updateCIComment(changeCIFlag, prevCISysID) {

//When CI is not changed & INC is not resolved.

if ([Link] != 6 && changeCIFlag == 'false') {

var getAffCI = new GlideRecord('cmdb_ci_server');

[Link]();

[Link]('sys_id', currentCISysID);

[Link]();

SCRIPT ACTION GYANINDRA YADAV


if ([Link]()) {

[Link] = "This CI is attached to " + incNumber + " on " +


[Link]() + ". Incident state is: " + [Link]() +
"\n" + [Link];

[Link]();

//When CI is changed & INC is not resolved.

if ([Link] != 6 && changeCIFlag == 'true') {

var getAffCI = new GlideRecord('cmdb_ci_server');

[Link]();

[Link]('sys_id', currentCISysID);

[Link]();

//Through we are updating the comments of existing Attached CI

if ([Link]()) {

[Link] = "This CI is attached to " + incNumber + " on " +


[Link]() + ". Incident state is: " + [Link]() +
"\n" + [Link];

[Link]();

SCRIPT ACTION GYANINDRA YADAV


//Through this we are updating the removed affected CI

[Link]();

[Link]('sys_id', prevCISysID);

[Link]();

if ([Link]()) {

[Link] = "This CI is removed from " + incNumber + " on " +


[Link]() + ". Incident state on the time of removal was : " +
[Link]() + "\n" + [Link];

[Link]();

//When INC is resolved.

if ([Link] == 6) {

var getAffCI = new GlideRecord('cmdb_ci_server');

[Link]();

[Link]('sys_id', currentCISysID);

[Link]();

if ([Link]()) {

[Link] = "This " + incNumber + " is resolved on " +


[Link]() + "\n" + [Link];

[Link]();

SCRIPT ACTION GYANINDRA YADAV


}

Save the Script Action.

Now create an Incident with an Affected CI and then check Comments fields
of that CI.

After inserting this record, let me check that CI.

As we can see, Comments field has been updated as we wanted to.

Let’s check 2nd condition. Let me change the CI to DatabaseServer2. Then we


will check both CI page.

SCRIPT ACTION GYANINDRA YADAV


DatabaseServer1 updated –

And check DatabaseServer2 –

It is also updated.

Let’s change the state of that incident to RESOLVED | 6 and then see the CI –

Thus, this use is completed.

Some other use cases of Script Actions:

1. When an incident is assigned to a specific assignment group, send a


custom email notification to the group members with dynamic content.
2. Automatically create a problem record when multiple incidents are
linked to a major incident or when an incident matches a certain
pattern (e.g., keyword match).
3. Send follow-up reminders to the incident assignee if the incident
remains in the “In Progress” state for more than 3 days.

SCRIPT ACTION GYANINDRA YADAV


4. When a security incident is created, trigger alerts to the Security
Operations team and automatically assign the incident based on the
impacted CI's owner.

Why is Script Action needed when Script


Include is already there?
While Script Actions and Script Includes both involve scripting in ServiceNow,
they serve very different purposes. Here’s a clear and industry-relevant
explanation of why Script Actions are needed, even when Script Includes
exist:

Purpose Difference

Feature Purpose

Script Reusable server-side logic—functions or classes that can be


Include invoked from Business Rules, Script Actions, UI Actions, etc.

A specific type of server-side script that runs asynchronously in


Script
response to an event. Used to handle event-driven background
Action
tasks like notifications, record creation, logging, etc.

Think of It This Way:

• Script Include = Reusable Logic Library

• Script Action = Event Handler

You can use a Script Include inside a Script Action, but not the other way
around.

SCRIPT ACTION GYANINDRA YADAV


Why Script Actions Are Needed (Even with Script Includes)

1. Event-Driven Processing

• Use Case: When a [Link] event is fired, you want to log the
problem details in an external table or send a notification.

• Why Not Just Script Include?: Script Includes don’t listen to events. You
still need Script Actions to respond to that event.

2. Asynchronous Execution

• Script Actions run in the background, keeping the main user interaction
fast and smooth.

• Script Includes are usually called synchronously (unless wrapped in


GlideAjax or other methods).

3. Decoupling Logic from Business Rules

• Instead of writing bulky logic directly in Business Rules or Workflows, you


can fire an event and let a Script Action handle it separately.

• This makes your code modular, maintainable, and testable.

Typical Usage Together

You can (and should) use Script Includes inside Script Actions for complex
logic:

var util = new MyReusableUtil(); // Script Include

[Link](current);

This keeps your Script Action clean and the logic centralized.

SCRIPT ACTION GYANINDRA YADAV


Summary

Can be triggered by Reusable


Feature Asynchronous?
Event? Logic?

Script No (unless
No Yes
Include wrapped)

Script Action Yes Yes Not directly

Conclusion:
Script Actions are necessary for handling event-based, asynchronous tasks,
which Script Includes alone cannot do. They complement each other—not
replace one another.

Here’s a visual flow to explain the relationship and roles of Script Actions and
Script Includes in ServiceNow, particularly in an ITSM use case:

SCRIPT ACTION GYANINDRA YADAV


Visual Flow: Script Action vs Script Include

[1] Incident Assigned to Group

[2] Business Rule detects change

[3] Event is fired (e.g., "[Link]")

[4] Script Action (Listens to the Event)

┌───────────────────────────────────
──────┐

│ Inside Script Action: │

│ - Prepare dynamic notification │

│ - OR create/update records │

│ - OR call integration │

└───────────────────────────────────
──────┘

[5] Calls a Script Include (Reusable logic)

┌────────────────────────────────────
─────────┐

│ Script Include: │

│ - Handles actual logic │

│ (e.g., build email body, assign user) │

SCRIPT ACTION GYANINDRA YADAV


│ - Can be reused elsewhere too │

└────────────────────────────────────
─────────┘

Explanation:

Step Component Role

1 User Action User assigns an incident to a group.

2 Business Rule Triggers an event when certain conditions are met.

3 Event System event fired, e.g., [Link].

4 Script Action Listens for that specific event and runs asynchronously.

5 Script Include Called from Script Action for reusable, testable logic.

Example Use Case:

When an incident is assigned to the Network Support group, the system fires
an event and a Script Action sends a custom email using logic from a Script
Include.

SCRIPT ACTION GYANINDRA YADAV

Common questions

Powered by AI

Script Actions can enhance incident management processes by automating responses to critical events. For instance, they can be configured to send customized email notifications to assignment groups when an incident is assigned to them, pulling dynamic content to personalize communication . Additionally, Script Actions can automatically create related problem records when certain incident patterns are detected, thereby streamlining issue resolution processes. They can also be used to send follow-up reminders if incidents remain unresolved for defined periods, ensuring accountability and timely incident management actions . These capabilities significantly improve incident handling efficiency and effectiveness by enabling proactive and automated operational responses .

Event-driven scripting using Script Actions offers several advantages over traditional synchronous scripting. Firstly, it allows scripts to execute in response to specific events, enabling highly targeted and context-aware responses, which is not possible with synchronous scripts that execute immediately upon a logical trigger . Secondly, the asynchronous nature of Script Actions ensures that long-running tasks do not interfere with user interactions, eliminating delays in the user interface and enhancing system responsiveness. Additionally, by responding to events, Script Actions help decouple logic from direct table interactions, facilitating more modular code that is easier to maintain and extend. In contrast, synchronous scripting tends to increase load and potential bottlenecks in processing, as tasks must complete before user control is returned . Thus, event-driven scripting enhances both performance and developer productivity by enabling more scalable and maintainable ServiceNow solutions .

Script Actions contribute significantly to efficient incident resolution in an ITSM framework like ServiceNow by enabling automated, contextually aware responses to system events. When an incident is created, updated, or resolved, Script Actions can automatically trigger actions such as updating records, sending notifications, or integrating with other systems. This automation reduces the risk of human error and speeds up processes that would otherwise require manual intervention. By running asynchronously, they do not disrupt user interactions and allow other critical operations to continue unabated . Additionally, Script Actions can directly contribute to faster root cause analysis and issue resolution by automating the creation of related records, such as problem records, when incident patterns are detected, thereby streamlining and expediting the incident management lifecycle . Overall, this leads to a more responsive ITSM system, improved service delivery, and higher customer satisfaction .

A developer might choose to use a Script Action over a Business Rule due to the asynchronous and event-driven nature of Script Actions. They enable the system to remain responsive while a task runs in the background, such as updating record comments in response to a specific event, like an incident's state change. This decouples the logic from direct table interactions, allowing for more modular and maintainable code . Additionally, Script Actions allow for complex conditions to be handled outside of strict table logic, facilitating cleaner separation and potential reuse of the logic in different contexts .

Script Actions and Script Includes serve distinct purposes in a ServiceNow environment. Script Actions are designed to handle event-driven, asynchronous processes. They are triggered when specific system events occur, such as a record being updated or an incident being resolved, and allow scripts to run in response. They can utilize server-side APIs and can operate in the background, ensuring a responsive user interface . Script Includes, on the other hand, are reusable server-side code blocks—consisting of functions or classes—that can be invoked by multiple script types, such as Business Rules or UI Actions. Unlike Script Actions, Script Includes do not listen for events and typically run synchronously unless explicitly made asynchronous using methods like GlideAjax . Together, Script Actions handle event-specific tasks while Script Includes provide reusable logic libraries .

The integration of Script Actions and Script Includes enhances service customization and automation by using Script Actions for event-driven processing while employing Script Includes for complex, reusable logic. For instance, when a Script Action is triggered by an event, it can invoke a Script Include to perform tasks like preparing the dynamic content of notifications or processing integrations with external systems. This setup allows developers to tailor the service behavior precisely to organizational needs, providing flexibility in response handling and ensuring that more complicated operations are managed efficiently without replicating code. It also supports agile development practices by allowing easy updates and maintenance to the underlying business logic found within Script Includes, while Script Actions manage event handling consistently across the system .

An ideal scenario for using Script Actions in ServiceNow would be when multiple incidents are merged into a major incident. In this case, a Script Action could be configured to automatically create a problem record when the major incident is identified or when it matches identified patterns. This process requires no immediate user interaction and can be handled in the background, making an asynchronous Script Action optimal. Handling it asynchronously ensures that system resources remain available for user-driven activities and helps in closing the loop on incident management by proactively addressing underlying issues through automated problem records . This approach minimizes human error and increases operational efficiency by automating complex workflows in response to specific triggers .

Script Actions support modularity and maintainability by separating event-driven processing from direct Business Rule logic. When a Business Rule triggers an event, a Script Action can handle the resultant tasks independently. This separation ensures that the main business logic remains clean and focused on its primary duty, while Script Actions manage background tasks such as notifications or data updates. By using events and Script Actions, developers reduce the complexity within individual Business Rules, making the system easier to modify and maintain . Furthermore, Script Actions can leverage Script Includes for reusable logic, helping maintain clean, DRY (Don't Repeat Yourself) code principles .

Script Actions improve user experience in ServiceNow by executing tasks asynchronously. This means that when a task, such as sending notifications or updating records, is triggered by an event, it runs in the background without blocking the user interface. As a result, users can continue to interact with the ServiceNow platform seamlessly, without experiencing delays or lag typically associated with synchronous operations. This asynchrony ensures that long-running processes or complex calculations are handled efficiently, enhancing overall system responsiveness and user productivity . By delegating resource-intensive tasks to Script Actions, the system maintains optimal performance and keeps user interactions fluid .

Script Includes serve as reusable libraries of functions or classes that can be invoked within Script Actions to perform complex logic or calculations. When a Script Action is triggered by an event, it can call specific functions from a Script Include to handle the detailed processing required for that event. This integration allows developers to keep the Script Actions clean and focused on event handling, while encapsulating complicated logic or repetitive tasks in Script Includes. This separation of concerns enhances code reusability and maintainability, enabling the same logic to be used across different scripts and actions without code duplication .

You might also like