logo

NJP

How to redirect user to an external page in UI Builder?

Import · Apr 27, 2022 · article

Using Service Portal it is easy to use the window $window object to easily redirect the user to any url. Although, it is not so straight forward when using UI builder. To achieve this, you can always hack the global window object via some currying (I will write that in another article). But it is not the recommended way. The recommended way is to dispatch an event with the uri in the payload and then use the OOB Link to destination event handler to redirect the user. Follow the step by step instruction to achieve this.

  1. Create a page script. Here you can do the logic to determine the uri the user needs to be redirected to.
    image
  2. There is a .emit() method in the api class. This method takes two arguments: the name of the event and the payload. The payload is a JavaScript Object literal. This can be declared in the script as such:
    function handler({api, event, helpers, imports}) { const uri = 'https://www.servicenow.com/'; api.emit('CUSTOM_REDIRECT_URL', {url: uri}); }
  3. Now this event has to be handled on the page. This will tell the application what to do when this event is fired. To do this go to the Body of your page layout and navigate to events:
    imageThen let us add a new handled event on the page. For this look for the handled events section on the events section and then click on add
    image
    After clicking on 'Add' enter the event label as the name of the event that you emitted in step 2 (of your page script). Then click on add.
    image
    Save the page.
    image
    After saving you will see this event in the Page Event mapping section.
    image
    Click on 'Add a new event handler' and a popup should appear. In the popup search for 'Link to destination' event handler.
    image
    In the popup click on 'Select destination' button and that will let you select further options.
    image
    There click on External URL and in the chosen route enter @payload.url as the key of the object in the emit() argument is 'url'. This will dynamically bind the payload that was emitted with the event in the script. Press OK when completed.
    image
  4. Now the script that was created in step 2 can be bound to an event on a component in the page. For eg. you can bind it to a click event. In my example, I added a button to the page and then on the button clicked event added the script as event handler.
    imageIn the event handler you should be able to find your script in the client script
    image
  5. Once you have bound the events with the event handler(s). You are good to go.

Labels:

image

View original source

https://www.servicenow.com/community/developer-articles/how-to-redirect-user-to-an-external-page-in-ui-builder/ta-p/2318090