SuiteScript 2.x Hello World

SuiteScript 2.x is a JavaScript API that offers a broad range of options for enhancing and extending NetSuite. You can use SuiteScript to customize the behavior of a page, create custom workflows, schedule tasks, and much more.

To help you understand how SuiteScript 2.x works, this topic walks you through the implementation of a basic customization. After you complete the steps in this topic, the system displays a “Hello, World!” message whenever you load a NetSuite task record.

This topic contains the following sections:

Key Concepts

Before proceeding with the steps in this topic, it may be useful to consider a few concepts and terms that are central to SuiteScript 2.x development. Some of these terms are referenced in the steps that appear later in this topic. You can read about these concepts now, or you can go straight to Step 1 Enable the Feature.

SuiteScript Versions

The sample script in this topic uses SuiteScript 2.0. A newer version, SuiteScript 2.1, is also available and supports new language features that are included in the ES2019 specification. You can write your scripts using either SuiteScript 2.0 or SuiteScript 2.1.

SuiteScript Reserved Words

Like most programming languages, SuiteScript includes a list of reserved words that you cannot use as variable names or function names in your scripts. For example, the var reserved word indicates a variable declaration, and the try reserved word indicates the start of a try-catch block. For more information, see SuiteScript Reserved Words.

SuiteScript 2.x Script Types and Entry Points

If you have written scripts before, you are probably used to thinking through basic questions prior to coding. These questions might include: What does the script need to accomplish? Should the script run in the browser or on the server? What specific event should trigger the script?

With SuiteScript 2.x, part of this process involves deciding which of the system’s predefined script types you should use. Each script type is designed for a specific type of situation and specific types of triggering events. The following are some of the available SuiteScript 2.x Script Types:

Each script type includes one or more entry points that are exclusive to that type. The entry point represents the juncture at which the system grants control of the NetSuite application to the script. When you include an entry point in your script, you tell the system that it should do something when that entry point is invoked. Specifically, you tell the system that it should execute a function defined within the script. This function is called an entry point function.

With many script types, the available entry points are analogous to types of events — various things that can happen — to trigger your script. For example, the client script type’s entry points represent events that can occur during a browser session. These entry points include fieldChanged(scriptContext), which represents a change to the value of a field, and pageInit(scriptContext), which represents the loading of a page. In comparison, the scheduled script type has only one entry point, called execute. It represents the point at which a schedule executes the script or a user acts manually to execute the script.

In the example used in this topic, you want a dialog alert to appear when a user working in a browser loads the NetSuite task record page. For that reason, this example uses the client script type and the pageInit entry point.

SuiteScript 2.x Modules

SuiteScript 2.x has a Modular Architecture. As one indication of this, all SuiteScript 2.x APIs are organized into a series of standard modules. Each module’s name reflects its functionality. For example, the N/record Module lets you interact with NetSuite records. The N/https Module lets you make https requests to external web services.

Most modules must be explicitly loaded by a script before the script can access that module’s APIs. At a high level, loading a JavaScript module is similar to importing a library in Java. It is a way of providing access to logic that is defined elsewhere. In an entry point script, you load a module by using the define Object. You list the modules that you want to load as an argument of the define function.

In contrast, some APIs are globally available. When an object, method, or function is globally available, it can be used even when you do not explicitly load the module to which it belongs. Globally available APIs are listed in SuiteScript 2.x Global Objects.

The example in this topic uses both approaches: It uses globally available APIs. It also uses a method that becomes available only after the appropriate module is loaded.

Entry Point Scripts Versus Custom Module Scripts

The example script in this topic is relatively simple. All of its logic is contained within one script file. However, you might want to create scripts that rely on logic defined in other script files. In SuiteScript 2.x, these supporting script files are known as custom module scripts.

In contrast, the primary script file — the one that identifies the script type, entry point, and entry point function — is known as an entry point script. The system imposes formatting requirements on entry point scripts that are different from those of custom module scripts. The remaining steps in this topic highlight some of the requirements that exist for entry point scripts.

Custom module scripts are not covered in this topic. For information about custom module scripts, see SuiteScript 2.x Custom Modules.

Step 1 Enable the Feature

Before you can complete the rest of the steps in this topic, the Client SuiteScript feature must be enabled in your NetSuite account.

If you are not sure whether the feature is enabled, you can check by navigating to Customization > Scripting > Scripts. If you can access that path, the feature is enabled. If the option does not appear, the reason could be that you do not have permission to access it, or that the menu path has been customized. If you are not sure, check with your account administrator.

The feature can be enabled by an account administrator or by a user with the Enable Features permission. To enable the feature, an authorized user should complete the following steps.

To enable the Client SuiteScript feature:

  1. Select Setup > Company > Enable Features.

  2. Click the SuiteCloud subtab.

  3. Locate the Client SuiteScript option. If the box is already checked, skip ahead to Step 2 Create the Script File. If it is not, check the box.

    Entry Point Scripts Versus Custom Module Scripts section of the SuiteScript 2.x Hello World page

    The system displays a window listing the terms of service.

  4. If you agree to the terms, scroll to the bottom of the window and click I Agree.

  5. Server SuiteScript is not required for the steps described in this topic. However, if you plan to do further SuiteScript development, consider checking the Server SuiteScript box. If you check the box, the system displays another window listing the terms of service. Click I Agree.

  6. Click Save.

Step 2 Create the Script File

Before proceeding, you must create a script file called helloWorld.js. To create this file, you can use either of the following approaches:

Create the Script Step by Step

The following steps walk you through the process of creating the helloWorld.js sample script. Many of the steps in this process are required for any entry point script.

To create the script file:

  1. Open a new file in your text editor of choice.

  2. Add two JSDoc tags @NApiVersion, and @NScriptType. After each JSDoc tag, add the appropriate value, as shown in the following snippet.

                  /**
     *@NApiVersion 2.0
     *@NScriptType ClientScript
     */
    
    ... 
    
                

    These tags reflect the following:

    • The version of SuiteScript you are using.

    • The script type you are using.

    Every SuiteScript 2.x entry point script must include these tags. For each tag, you can include only one value. For more information and a list of valid values, see SuiteScript 2.x JSDoc Tags.

  3. Add the define Object. Every entry point script must use this function.

    Use [‘N/ui/dialog’] as the define function’s first argument. This first argument is an array of string values representing the modules that the function should load.

                  ...
    define(['N/ui/dialog'],
    
        // In Step 4, you will add additional code here.
    
    ); 
    
                

    The N/ui/dialog Module includes methods that display various types of dialogs. You load this module so that the script can use one of these methods.

  4. Declare a callback function. The callback function is the define function’s second argument. Give this function one argument called dialog.

                  ...     
        function(dialog) { 
    
            // In Step 5, you will add additional code here.
    
        } 
    ... 
    
                

    If you are not familiar with callback functions, remember that this function will contain all of the script’s other logic. Additionally, remember that the number of arguments used by the callback function must equal the number of modules loaded by the define function. Each argument is an object that lets you access the module it represents. As a best practice, give each argument a name similar to that of the corresponding module.

    In this example, the define function loads only one module, so the callback function has only one argument.

  5. Within the callback function, declare a function called helloWorld.

                  ...
            function helloWorld() {
    
                // In steps 6-10, you will add additional code here.
    
            }
    ... 
    
                

    Later, you designate the helloWorld function as the script’s entry point function. Every entry point script must have an entry point function.

    A function is considered an entry point function only if it is linked to an entry point. You create this link in Step 11.

  6. Within the entry point function, create an object named options.

    Many SuiteScript 2.x methods either require or can accept a plain JavaScript object as their argument. The method that you use to create the “Hello, World!” dialog falls into this category. This method accepts an object that has two parameters: title and message.

                  ... 
                var options = {
                    title: 'Hello!',
                    message: 'Hello, World!'
                };
    ... 
    
                
  7. Add a try/catch statement. This statement is not required. However, this approach lets your script handle errors gracefully. That is, if an error occurs and is handled by a try/catch statement, your script — and any others that are deployed on the page — can continue executing. Using a try/catch statement can also help you understand why problems occur. Note that the try/catch keywords are part of JavaScript and not specific to SuiteScript 2.x.

    A basic try/catch statement consists of two parts. The try block holds code that you want to execute. The catch block holds logic that should execute if JavaScript errors are encountered during the try block.

    Add the try/catch statement after the object that you created in Step 6.

                  ...
                try {
    
                    // In steps 8 and 9, you will add additional code here.
    
                } catch (e) {
    
                    // In Step 10, you will add additional code here.
    
                }
    ... 
    
                
  8. For the first action of the try block, invoke the N/ui/dialog Module’s alert() method. This method creates a dialog with a title, a message, and an OK button.

    You invoke this method by using the object which, in Step 4, you named dialog. You also use the method’s name, alert. To define the dialog’s title and message, pass in the object titled options.

                  ...
                    dialog.alert(options);
    ... 
    
                

    For more details about this method, see the dialog.alert(options) reference page. Note that the title of the dialog.alert(options) reference page matches the code you have added to your script. However, be aware that the reference pages for standard module methods may not always reflect your naming conventions. For example, if you had specified an argument named message when you declared your callback function, you would invoke the alert method using the expression message.alert(options).

    Similarly, note that within the documentation, each method’s argument is typically referenced as an object titled options. However, in your script, you can give the object any name. You can also create the object directly, as part of the process of invoking the method.

  9. Add logic to create a log entry when the dialog displays successfully. To do this, use the globally available log.debug(options) method.

    The debug() method is called on the log object. Unlike the dialog object, which you had to take steps to access, the log object is made available to every script. For that reason, you don’t give this object a name, so you can always write log.debug to call this method.

    This method takes an object that has two properties: a title and a detailed message. This time, create the object directly. Contrast this style with the way you created an object in Step 5, then passed that object by name to the alert() method.

                  ...
                    log.debug ({
                        title: 'Success',
                        details: 'Alert displayed successfully'
                    });
    ... 
    
                

    The log entry is created in the UI when a user triggers the dialog alert. An explanation of how to find the log is covered in Step 5 Test the Script.

  10. In the catch block, add logic to create a log entry if an error is thrown. Use the globally available log.error(options) method. The log.error() method is similar to the log.debug() method. The only difference is that, with log.error(), the log entry is classified as an entry of type error, instead of debug.

                  ...
                    log.error ({ 
                        title: e.name,
                        details: e.message
                    });           
    ... 
    
                
  11. Immediately after the entry point function, add a return statement. In every SuiteScript 2.x entry point script, the return statement must include at least one line that has two components:

                  ...
            return {
                pageInit: helloWorld
            };
    ... 
    
                

    Because of this reference, helloWorld is considered an entry point function.

    Although this script uses only one entry point, a return statement can include multiple entry points. Using multiple entry points is permitted if they all belong to the script type identified by the @NScriptType tag at the top of the file. For example, in addition to pageInit(scriptContext), the client script type also includes saveRecord(scriptContext). So, if you wanted the script to take one action when the page loads and another action when the user clicks Save, you could use both entry points. For an example of a script that uses multiple entry points, see SuiteScript Client Script Sample.

  12. Save the file, naming it helloWorld.js.

Copy the Full Script

This section shows the full sample script. If you haven’t already created the script file by using the steps described in Create the Script Step by Step, copy and paste the following code into a text file. Save the file and name it helloWorld.js.

          /**
 *@NApiVersion 2.0
 *@NScriptType ClientScript
 */


define(['N/ui/dialog'],

    function(dialog) {

        function helloWorld() {

            var options = {
                title: 'Hello!',
                message: 'Hello, World!'
            };
        
            try {
           
                dialog.alert(options);
           
                log.debug ({
                    title: 'Success',
                    details: 'Alert displayed successfully'
                });
        
            } catch (e) {
           
                log.error ({ 
                    title: e.name,
                    details: e.message
                });           
            } 
        }
              
    return {
        pageInit: helloWorld
    };
}); 

        

Step 3 Upload the Script File to NetSuite

After you have created your entry point script file, upload it to your NetSuite File Cabinet.

To upload the script file:

  1. In the NetSuite UI, go to Documents > File > SuiteScripts.

  2. In the left pane, select the SuiteScripts folder and click Add File.

  3. Follow the prompts to locate the helloWorld.js file in your local environment and upload it.

Be aware that even after you upload the file, you can edit it from within the File Cabinet, if needed. For details, see Editing Files in the File Cabinet.

Step 4 Create a Script Record and Script Deployment Record

In general, before an entry point script can execute in your account, you must create a script record that represents the entry point script file. You must also create a script deployment record.

The script deployment record contains part of the logic that determines when the script executes. Some of that logic is contained within the script, by the entry point that the script uses. For example, by using the pageInit(scriptContext) entry point, you tell the system that the script should execute when a page loads. However, you must also identify the specific page which, when loaded, causes the script to execute. Stated another way, you must tell the system which record type this script should execute on. To do that, you use the script deployment record.

These records can be created programmatically. You can also create them in the UI, as described in the following procedure.

To create the script record and script deployment record:

  1. Go to Customization > Scripting > Scripts > New.

  2. In the Script File dropdown list, select helloWorld.js.

    If you had not yet uploaded the file, as described in Step Three, you could upload the file from this page. With your cursor, point to the right of the dropdown list to display a plus icon. Clicking this icon opens a window that lets you upload a file.

  3. After you have populated the dropdown list, click the Create Script Record button.

    In response, the system displays a new script record, with the helloWorld.js file listed on the Scripts subtab.

  4. Fill out the required body fields as follows:

    • In the Name field, enter Hello World Client Script.

    • In the ID field, enter _cs_helloworld.

  5. Click the Deployments subtab. You use this subtab to create the deployment record.

  6. Add a line to the sublist, as follows:

    • Set the Applies to dropdown list to Task. If you want the dialog to appear when a different type of record loads, select another record type from the list.

    • In the ID field, enter _cs_helloworld.

    Leave the other fields set to their default values. Note that the Status field is set to Testing. This value means that the script does not deploy for other users. If you want to change the deployment later and make this customization available to all users, edit the deployment and set the status to Released.

  7. Click Save.

    The system creates the script and script deployment records.

Step 5 Test the Script

Now that the script is deployed, you should verify that it executes as expected.

To test the script:

  1. Verify that the dialog alert appears when it should:

    1. Open a task record by going to Activities > Scheduling > Tasks > New.

      If the script is working properly, the system displays a dialog alert.

      Step 5 Test the Script section of the SuiteScript 2.x Hello World page
    2. Confirm and close the dialog by clicking OK.

  2. Verify that the expected log entry has been saved to the script deployment record:

    1. Go to Customization > Scripting > Script Deployments.

    2. Locate your deployment, and click View.

      Step 5 Test the Script section of the SuiteScript 2.x Hello World page
    3. Click the Execution Log subtab.

      The subtab should show an entry similar to the following.

      Step 5 Test the Script section of the SuiteScript 2.x Hello World page

      The same entry also appears on the Execution Log of the script record.

      If an error had been encountered, the error log entry you created would be displayed instead of the debug entry.

Next Steps

Now that you have deployed your first script, consider browsing other topics in SuiteScript 2.x API Introduction. Or, if you want to experiment with other script samples, try the following:

Related Topics

SuiteScript 2.x API Introduction
SuiteScript 2.x Script Basics
SuiteScript 2.x Anatomy of a Script
SuiteScript 2.x Script Creation Process
SuiteScript 2.x Advantages
SuiteScript 2.x Terminology
SuiteScript 2.x Developer Resources
SuiteScript Reserved Words
SuiteScript Versioning Guidelines

General Notices