Aug 10, 2025

How to Create HTML File from an Incident in ServiceNow

In ServiceNow, you may need to export Incident details into an HTML file for reporting, sharing, or archiving purposes. This tutorial walks you through the process of generating an HTML file directly from an Incident record using a Script Include and a UI Action.

Why Generate HTML from ServiceNow Incident?

  • Share a styled, readable version of Incident details
  • Archive Incidents outside ServiceNow
  • Create printable reports with a clean layout

Step 1: Create a Script Include

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

    generateHTML: function(incidentSysId) {
        var inc = new GlideRecord("incident");
        if (inc.get(incidentSysId)) {
            var html = '<!DOCTYPE html>';
            html += '<html lang="en">';
            html += '<head><meta charset="UTF-8">';
            html += '<title>Incident ' + inc.number + '</title></head>';
            html += '<body>';
            html += '<h1>Incident Details</h1>';
            html += '<p><strong>Number:</strong> ' + inc.number + '</p>';
            html += '<p><strong>Short Description:</strong> ' + inc.short_description + '</p>';
            html += '<p><strong>Description:</strong> ' + inc.description + '</p>';
            html += '<p><strong>Priority:</strong> ' + inc.priority + '</p>';
            html += '<p><strong>State:</strong> ' + inc.state.getDisplayValue() + '</p>';
            html += '</body></html>';
            return html;
        }
        return null;
    },

    type: 'IncidentHTMLGenerator'
};

Step 2: Create a UI Action

var htmlContent = new IncidentHTMLGenerator().generateHTML(current.sys_id);

if (htmlContent) {
    var sa = new GlideSysAttachment();
    var contentStream = new java.io.ByteArrayInputStream(new java.lang.String(htmlContent).getBytes("UTF-8"));
    sa.write(current, "Incident_" + current.number + ".html", "text/html", contentStream);
    gs.addInfoMessage("HTML file created and attached to this Incident.");
} else {
    gs.addErrorMessage("Incident not found or failed to generate HTML.");
}

action.setRedirectURL(current);

Step 3: Test the Functionality

  1. Open any Incident record in ServiceNow
  2. Click the Generate HTML button
  3. Check the Attachments section — your .html file will be there
  4. Download and open it in your browser

Conclusion

By combining a Script Include and a UI Action, you can easily generate an HTML version of any Incident in ServiceNow. This is especially useful for reporting, sharing with non-ServiceNow users, and creating clean, printable reports.

💡 Pro Tip: You can style the HTML output with CSS for a professional look before attaching it.

Jun 29, 2023

Create Text file and send to MID Server in ServiceNow

ServiceNow Export Set offers to export data in a limited format, as shown below. This article will discuss how to create a .txt file and export it to MID Server.

To create a text file and send it to a MID Server in ServiceNow, you can combine the file creation and MID Server file transfer steps

Create a text file and attach to the MID Server Attachments (ecc_agent_attachment) record.

Below is the Script Include to create the .txt file and transfer to the MID Server. The Script Include have some functions.
/* esline no-undef:error,no-unused-vars:warning */
var FileTransferUtil = Class.create();
FileTransferUtil.prototype = {
    initialize: function() {},
    CreateTextFilefunction() {
        var fileContent = "This is a sample text file";
        fileName = 'CustomeText.txt';

        var eccAttachment = new GlideRecord('ecc_agent_attachment');
        eccAttachment.initialize();
        eccAttachment.name = 'Export Set Attachment';
        eccAttachment.short_description = 'Exporting Custom Text File:' + fileName;
        var eccAtt_sys_id = eccAttachment.insert();

        var attachment = new GlideSysAttachment();
        var attachmentRec = attachment.write(eccAttachment, fileName, "text", fileContent);
        if (!gs.nil(attachmentRec)) {
            var xmlString = '<?xml version="1.0" encoding="UTF-8"?>' +
                '<parameters>' +
                '<parameter name=\"stream_relay_response_topic\" value=\"ExportSetResult\"/>' +
                '<stream_relay_source attachment_sys_id=\"' + attachmentRec + '\" type=\"AttachmentSource\"/>' +
                '<stream_relay_transform attachment.table_sys_id=\"' + eccAtt_sys_id + '\" order=\"0\" stream_relay_transfer_progress_interval=\"150\" type=\"AttachmentProgressTransformer\"/>' +
                '<stream_relay_sink path="\/' + fileName + '\" type=\"FileSink\"/>' +
                '</parameters>';
            //stream_relay_sink path update as per requirement
            // agent/export/ is base folder
            // Create ECC Record
            var eccQueue = new GlideRecord('ecc_queue');
            eccQueue.initialize();
            eccQueue.agent = 'mid.server.XXXXXXXXX';//MID Server Name
            eccQueue.topic = 'StreamPipeline';
            eccQueue.queue = 'output';
            eccQueue.state = 'ready';
            eccQueue.payload = xmlString;
            eccQueue.insert();
        }
    },
    type: 'FileTransferUtil'
};
Below is how to consume the Script Include

var util=new FileTransferUtil();
util.CreateTextFile();

May 28, 2023

Async Business Rules in ServiceNow

There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules

    Business rules are usually executed synchronously, meaning they run in sequence and block further execution until completion. While effective for quick operations, this can slow down performance for longer tasks.

Async Business Rules solve this problem by executing in the background, ensuring that the main transaction completes quickly and the user interface remains responsive.


How Async Business Rules Work

  1. Trigger – Like After Business Rules, Async rules execute after a database operation (insert, update, delete, or query).
  2. Separate Thread – They run on a separate processing thread, allowing the main transaction to finish without waiting.
  3. sys_trigger Table – When triggered, ServiceNow creates a record in the sys_trigger table containing:
    • A reference to the Async Business Rule
    • The record (current) to process
  4. Scheduler Execution – Jobs are picked up by the scheduler as soon as possible for execution.

Execution Flow

  • Record change triggers the Async Business Rule.
  • ServiceNow logs the job in sys_trigger.
  • Scheduler processes the job in the background.
  • A new scripting environment is created.
  • The current record is loaded at execution time for processing.

Limitations of Async Business Rules

  • No Access to Previous Record Values – Async Business Rules cannot access the previous state of a record.
  • GlideElement Method Restrictions – The following methods do not work inside Async rule scripts:
    • changes()
    • changesTo()
    • changesFrom()
  • Condition Field Behavior – While these methods don’t work in the script directly, the condition builder and advanced condition field do support them.

Viewing Async Business Rules in ServiceNow

  1. Navigate to System Scheduler > Scheduled Jobs.
  2. Look for job names starting with ASYNC.
  3. Note: They execute quickly, so they may be hard to catch in the list.

Benefits of Async Business Rules

  • Prevents UI freezing during long-running operations.
  • Improves system performance by running processes in the background.
  • Keeps the main transaction fast and responsive.
  • Ideal for tasks that don’t require immediate user feedback.


FAQ – Async Business Rules in ServiceNow


1. When should I use Async Business Rules in ServiceNow?

Use Async Business Rules for background tasks that do not require immediate feedback to the user, such as sending notifications, updating related records, or triggering integrations. They improve performance by preventing UI delays.

2. What’s the difference between Async and After Business Rules?

After Business Rules run synchronously after a database operation and block the transaction until finished.
Async Business Rules also run after a database operation, but they execute on a separate thread in the background, allowing the main transaction to complete quickly.

3. Why doesn’t changes() work in Async Business Rules?

Async Business Rules do not have access to the previous version of a record, so GlideElement methods like changes(), changesTo(), and changesFrom() will not work inside their scripts. However, these methods still work in the condition builder and advanced condition field.

4. How do I view Async Business Rules in ServiceNow?

Go to System Scheduler > Scheduled Jobs and look for entries starting with ASYNC. These represent queued Async Business Rules, but they may disappear quickly because they execute almost instantly.

5. What are the benefits of Async Business Rules?

They prevent UI freezing, improve system responsiveness, allow long-running processes to run in the background, and reduce load on primary execution threads. 





 

 

Display Business Rules in ServiceNow

 There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules

In ServiceNow, Display Business Rules are a type of business rule that allows you to control the visibility and behavior of form elements (fields, sections, related lists, etc.) on a form in the user interface.

Display Business Rules run when a user requests a record/load a form, data has been retrieved from the database, and before the form is presented back to the user.

Display Business Rules use g_scratchpad object to store server-side script results and send them to the client-side. Display Business Rules execute their logic when a form loads and a record is loaded from the database. They must complete execution before control of the form is given to a user.

Client-Scripts only have access to fields and field values for fields on the form and not all of the fields from the database. Use the g_scratchpad object to pass data to the client-side without modifying the form. The g_scratchpad object has no default properties.

How to use Display Business Rules:

  • Create a display business rule as per your requirement (conditions).
  • Use g_scratchpad object to store data from server-side and send to the client-side.
  • Use g_scratchpad object properties to manipulate/process form-level data.
// From client script 
if(g_scratchpad.someName == "someValue") { 
  //do something special 
}


After Business Rules in ServiceNow

 There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules
In ServiceNow, an "after" Business Rule is a customization mechanism used to perform automated actions or logic after a record is inserted, updated, or deleted in a specific table. It is a server-side script that executes after the database transaction has occurred.

The purpose of an "after" business rule is to extend and customize the behavior of the platform by defining additional actions or validations based on changes made to records. It allows you to automate processes, enforce business rules, perform calculations, update related records, send notifications, or integrate with other systems after the record has been saved in ServiceNow. It gives you the ability to write server-side scripts using JavaScript to interact with the ServiceNow platform and perform various operations on the affected record or related records.

By utilizing "after" business rules effectively, you can enhance the functionality and automation capabilities of ServiceNow, aligning it with your organization's unique requirements and processes.

Here are some key points about "after" business rules in ServiceNow:
  • Event Trigger: An "after" business rule is triggered after a specific database operation, such as "insert", "update", or "delete", is performed on a record in the associated table.
  • Execution Timing: The script associated with the "after" business rule executes after the database transaction has completed. This means that the record changes have already been committed to the database.
  • Server-Side Execution: "After" business rules run on the server-side of the ServiceNow platform. They are implemented using server-side JavaScript and have access to the Glide API, which provides a wide range of functionalities for interacting with the platform's data and services.
  • Context and Conditions: You can define conditions or criteria for the business rule to execute. These conditions can be based on the values of specific fields, the user who made the changes, or any other relevant data in the record.
  • Script Logic: The script associated with the "after" business rule can perform a variety of operations, such as querying and updating other records, calculating values, validating data, sending notifications, logging information, or triggering workflows.
  • Extension and Customization: "After" business rules allow you to extend and customize the behavior of ServiceNow beyond the out-of-the-box functionality. They provide a way to implement specific business logic or automate actions based on changes to records.


Some common use cases for "after" business rules include:

  • Field calculations or derivations: You can use the business rule to compute values for certain fields based on the values of other fields. For example, you can automatically calculate the total cost of an order based on the quantity and unit price.
  • Data validation: You can validate the data entered in the record against certain criteria or business rules. For instance, you can check if a user is eligible for a specific service based on their department or role.
  • Sending notifications or alerts: The business rule can trigger notifications or alerts to relevant stakeholders based on the changes made to the record. This can include sending emails, generating notifications within the ServiceNow platform, or triggering external integrations.
  • Updating related records: You can use the business rule to update other records that are related to the changed record. For example, when an incident is resolved, you can automatically update the associated change request or notify the requester.
  • Logging or auditing: The business rule can log the changes made to the record or generate audit records for tracking purposes. This can help in maintaining a record of data modifications and monitoring system activity.