The helpers API provides general functionality that is common across page scripts, eliminating the need to write scripts for simple functionality such as opening and closing a modal.

This API is only available to page scripts, it is not available in any other UI Builder scripts including:
  • component property value scripts
  • component visibility scripts
  • event payload scripts
  • UX client script includes

helpers - helpers.modal.close(String modalId)

Closes the specified modal on the current page.

Table 1. Parameters
Name Type Description
modalId String Modal component ID of the modal to close. Component IDs are auto generated when a component is dragged and dropped on the UI Builder stage. You can locate the ID on the property page.
Table 2. Returns
Type Description
None

Example

This example shows closing a modal with a component ID that ends with alert-modal.

function handler({api, event, imports, helpers}) {
  helpers.modal.close("[component-id$='alert_modal']")
}

helpers - helpers.modal.open(String modalId, Object options)

Opens the specified modal on the current page.

You can only display one modal at a time within a page. If a modal is currently open, and you call this method, the existing modal is hidden and the new modal appears.

Table 4. Returns
Type Description
None

Example

This example shows opening a modal with ca omponent ID that ends with alert-modal.

function handler({api, event, imports, helpers}) {
  helpers.modal.open("[component-id$='alert_modal']")
}

helpers - helpers.navigate.setRouteParams(Object params)

Passes the specified parameters down to other components on the same page.

Use this method in any page component that wants to add a parameter in a URL. You may want to add a parameter to a URL when another component needs to know the current value of that parameter when it changes, so it can react to it. For example, use this method to pass the selectedIndex of a tab component so it reflected in the URL to give focus to that tab.

Table 5. Parameters
Name Type Description
params Object Key-value pairs of optional parameters to pass to other components.

This must be a plain, flat object with only primitive values. Array or object references are ignored and not added to the URL. All specified keys  must be part of  the optional parameters  in the route configuration or they are also ignored. For additional information on optional parameters, see Create a page in UI Builder.

Table 6. Returns
Type Description
None

Example

This code example shows how to append the URL params/selected-tab-index/2. Note that the parameter in the actual URL is changed from camel case to snake case, so selectedTabIndex becomes selected-tab-index.

function handler({api, event, helpers, imports}) {  
  helpers.navigate.setRouteParams({'params': {'selectedTabIndex':  2}});  
} 

helpers - helpers.navigate.to(String route, Object fields, Object params, Boolean redirect, Boolean passiveNavigation, String targetRoute)

Navigates from one screen to another based on the specified route and field information. URL changes and the respective screen loads are observed.

Table 8. Returns
Type Description
None

Example

This example shows how to navigate to a page passing just the route parameter.

function handler({api, event, imports, helpers}) {
  helpers.navigate.to('test');
}

Example

This example shows how to navigate to a page passing the route and fields parameters.

function handler({api, event, imports, helpers}) {
  helpers.navigate.to('test', {'key': 'value'});
}

Example

This example shows how to navigate to a page passing the route, fields, and params parameters.

function handler({api, event, helpers, imports}) {
  helpers.navigate.to('test', {'key': 'value'}, {'first': 'FirstName', 'last': 'Last Name'});
}

helpers - helpers.screen.updateStatus(Object statusObj)

Enables pages to report their status updates, such as title, icon, dirty state, message, and error changes.

Status updates are reported to WorkspaceChrome or AppShell, whichever the outer layer is, and acting as the host.

Table 9. Parameters
Name Type Description
statusObj Object Payload to send to the current page to report that the content has been updated.
Valid values:
  • dirtyModalId: (String) ID of the modal that has changed.
  • hasError: (Boolean) Flag that indicates that there are errors on the page.
  • hasUpdate: (Boolean) Flag that indicates that there were updates to the page.
  • icon: (String) Name of the updated or new icon.
  • isDirty: (Boolean) Flag that indicates whether the page is dirty (values have changed).
  • message: (String) Updated/new message.
  • screenKey: (String) ID of the screen on which the change occurred. Every screen has a screenKey as a property on the screen macroponent inside sn-canvas-screen.
  • status: (String) Status operation for this action. This value must be one of the following: inserted, deleted, saved, or closed.
  • title: (String) Updated/new display title.
  • tooltipPreview: (JSON) Updated or new tool tip. For example, tooltipPreview : { primaryTitle, secondaryContent: {} }
Table 10. Returns
Type Description
None

Example

screen.updateStatus({'dirtyModalId': 'customModalId', 'isDirty': true});

helpers - helpers.snHttp(String url, Object options)

Makes an HTTP request to the ServiceNow instance and returns a promise with the results.

Note: There is a known issue where objects named options are omitted from the HTTP response.
{
  options: {},
  otherFields: {}
}

becomes

{
  otherFields: {}
}

Example

The following example show how to call snHttp() which returns a promise.

function handler({api, event, helpers, imports}) {
  helpers.snHttp('/api/now/table/u_movie', {method: 'GET'})
    .then(({response}) => {
      // do something with the table data
    })
    .catch(({error}) => {
      const message = `Error: ${error.data.error.message}`;
      console.error(message);
      api.emit('NOW_UXF_PAGE#ADD_NOTIFICATIONS', {
        id: 'alert5',
        status: 'high',
        icon: 'info-circle-outline',
        content: message,
        action: { type: 'dismiss' }
    });
  });
}

Example

The following example show how to call snHttp() using async and await.

async function handler({helpers}) {
  try {
    const result = await helpers.snHttp('/api/now/table/u_movie', {method: 'GET'});
  } catch ({error}) {
      const message = `Error: ${error.data.error.message}`;
      console.error(message);
      api.emit('NOW_UXF_PAGE#ADD_NOTIFICATIONS', {
        id: 'alert5',
        status: 'high',
        icon: 'info-circle-outline',
        content: message,
        action: { type: 'dismiss' }
      });
  }
}

Example

The following example show how to set up a POST request.

function handler({api, helpers, event, imports}) {
  helpers
    .snHttp("/api/now/table/incident", {
      method: "POST",
      body: {
        description: "Sample description",
        close_notes: "Sample close notes",
        order: "-1"
      }
    })
    .then(({ response }) => {
      // handle POST request response
    })
    .catch(({ error }) => {
      // handle POST request errors
    });
}

Example

The following example show how to set up a PUT request.

function handler({api, helpers, event, imports}) {
  helpers
    .snHttp("/api/now/table/incident/a83820b58f723300e7e16c7827bdeed2", {
      method: "PUT",
      body: {
        activity_due: "1970-04-02 18:26:17"
      },
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/xml"
      }
    })
    .then(({ response }) => {
      // handle PUT request response
    })
    .catch(({ error }) => {
      // handle PUT request errors
    });
}

helpers - helpers.timing.clearInterval(Number timeoutId)

Cancels the execution of the function that was scheduled through a prior setInterval() call.

Table 13. Parameters
Name Type Description
timeoutId Number Unique identifier of the scheduled function to clear. This value is returned by the corresponding setInterval() call.
Table 14. Returns
Type Description
None

Example

This example shows using clearInterval() to cancel a timing operation that was previously set using thesetInterval() method. This function could be invoked by a user clicking a Disable Auto-refresh button on a page.

function handler({api, helpers}) {
  api.setState('intervalId', ({currentValue}) => {
    if (currentValue > -1) {
      helpers.timing.clearInterval(currentValue);
    }
    return -1;
  });
}

helpers - helpers.timing.clearTimeout(Number timeoutId)

Cancels the execution of the function that was scheduled through a prior setTimeout() call.

Table 15. Parameters
Name Type Description
timeoutId Number Unique identifier of the scheduled function to clear. This value is returned by the corresponding setTimeout() call.
Table 16. Returns
Type Description
None

Example

This code example shows how to terminate a timer with the specified timeoutId.

function handler({api, helpers}) {
  api.setState('timeoutId', ({currentValue}) => {
    if (currentValue > -1) {
      helpers.timing.clearTimeout(currentValue);
    }
    return -1;
  });
}

helpers - helpers.timing.setInterval(Function fn, Number delay)

Repeatedly executes the specified function, using the specified delay value as the interval between function calls.

Unlike the native JavaScript setInterval() method, this method does not support passing a code string to evaluate as the first argument. Any additional arguments are passed to the function itself.

Table 17. Parameters
Name Type Description
fn Function Function to repeatedly execute.
delay Number Length of the time-interval between each function execution.

Unit: Milliseconds

Table 18. Returns
Type Description
Number Unique identifier of the function execution operation. Use this value in the helpers - helpers.timing.clearInterval(Number timeoutId) method if you need to cancel this operation.

Example

This code example shows how to refresh the timestamp on a page every second. This function could be invoked by a user clicking an Enable Auto-refresh button on a page.

function handler({api, helpers}) {
  // Every one second, refresh the value of current timestamp client state parameter
  const intervalId = helpers.timing.setInterval(() => {
    api.setState('currentTimestamp', new Date().toString())
  }, 1000);

  // The interval ID is kept in state to use when calling the helpers.timing.clearInterval() method at a later point
  api.setState('intervalId', intervalId);
}

helpers - helpers.timing.setTimeout(Function fn, Number delay)

Executes the specified function, after the specified delay.

Unlike the native JavaScript setTimeout() method, this method does not support passing a code string to evaluate as the first argument. Any additional arguments are passed to the function itself.

Table 19. Parameters
Name Type Description
fn Function Function to execute.
delay Number Length of the time to wait before calling the specified function.

Unit: Milliseconds

Table 20. Returns
Type Description
Number Unique identifier of the function execution operation. Use this value in the helpers - helpers.timing.clearTimeout(Number timeoutId) method if you need to cancel this operation.

Example

This code example shows how to set a 20 minute timer. You could associate this function with a button Remind me in 20 minutes.

function handler({api, helpers}) {
  const timeoutId = helpers.timing.setTimeout(() => {
    api.emit('NOW_UXF_PAGE#ADD_NOTIFICATIONS', {
      id: 'alert5',
      status: 'high',
      icon: 'info-circle-outline',
      content: 'Try to look away at something that is 20 feet away from you for a total of 20 minutes.',
      action: { type: 'dismiss' }
    });
  }, 20 * 60 * 1000);

  // The timeout ID is kept in state to use when calling the helpers.timing.clearTimeout() method at a later point
  api.setState('timeoutId', timeoutId);
}

helpers - helpers.translate(String message, String tokens)

Asynchronously retrieves and translates the specified message based on the current user's session language.

You can use this method with the api - setState(String stateParam, Any value) to bind the translated value to other fields on the page.

Note: You can call this method using a promise or async and await. The code examples below show both implementations.
Table 21. Parameters
Name Type Description
message String Message to translate.
tokens String Optional. Comma-separated list of parameters to use for replacing string variables.

For example:

helpers.translate('Text {0} {1}', 'to', 'translate'); 
Table 22. Returns
Type Description
String Translated text string.

Example

The following example shows how to pass in table field references to embed in the corresponding variables in a string, using a promise.

function handler ({api, helpers}) {
  helpers.translate('Welcome {0} {1}!', user.firstName, user.lastName)
    .then((translatedText) => {
      api.setState('greeting', translatedText);
    });
}

Example

The following example shows how to use async and await in your function instead of a promise.

async function handler ({api, helpers}) {
  const translatedText = await helpers.translate('Welcome to {0}', 'ServiceNow');
    api.setState('greeting', translatedText);
}