Redirect to a new URL on Service Portal on click of Server Side UI Action
Hi All,
I had hard time recently to find a solution to redirect to URL when user clicks on a Server Side UI Action on Service Portal in scoped application. Basically what i was trying to achieve is to create a UI action which copies the existing record and then navigates to newly created record and all that on Service Portal.
I noticed there are several challenges here:
1- UI Action can only be Server Side if you have to display it on Service Portal which already limits your options for url re-direction.
2- action.setRedirectURL() or gs.setRedirect() works in Server Side UI Actions but is not supported on Service Portal
3- setPreference on Server Side does not work on Portal either, you need to use savePreference instead.
4- UI Script does not have access to getPreference method.
Here is the solution which I developed to overcome the challenges and get the redirection as described in title.
UI Action
Client: False (as its server side UI action which is visible on Service Portal)
Script: After all your code for functionality you would like to develop just add two lines at the bottom as below in the script.
var url="<your service portal URL where you would like to redirect>";
gs.getUser().savePreference("sfRedirectPortal",url);
the above code sets your url in user preference "sfRedirectPortal" which is later retrieved to redirect.
UI Script
Create a ui script as follows:
UI Type: All
Script:
redirectToUrl();
function redirectToUrl() {
grUserPreference = new GlideRecord('sys_user_preference');
grUserPreference.addQuery('user', top.window.NOW.user_id); // picking up current user as g_user doesnt work here.
grUserPreference.addQuery('name', 'sfRedirectPortal');
grUserPreference.query(response);
function response(result) {
var url = '';
var sflastRedirect = '';
if (result.next()) {
url = result.value;
sflastRedirect = localStorage.getItem("sflastRedirect");
if (url != "" && top.window.location.toString().indexOf(url) == -1 && (grUserPreference.sys_updated_on > sflastRedirect || sflastRedirect == null)) {
localStorage.setItem("sflastRedirect", grUserPreference.sys_updated_on);
top.window.location = url;
}
}
}
}
above code retrieves user preference using glide record (note that getPreference does not work in UI Script/Service Portal) and then is used to redirect.
Basically in this solution this UI Script is executed each time Service Portal form is reloaded or a UI action is clicked.
Please try this solution and share your feedback.
Cheers
Syed Faheem.
Principal Technical Consultant
ServiceNow.
https://www.servicenow.com/community/now-platform-articles/redirect-to-a-new-url-on-service-portal-on-click-of-server-side/ta-p/2308364