Service Portal: Setting variables via URL

The other day, a post was made, asking how to do this
and I had to answer. I knew you could read the URL via $window but that isn't available in client scripts. How can this be done?

I came up with the following solution.

Create a Variable type "macro", with a widget that has the following client script;

function($scope, $window) {
// This is the controller, we've included
// $scope in the function above because
// it's easy to work with
var c = this;
// We are going to simplify accessing
// g_form within the client script by
// setting it as a variable named g_form
var g_form = $;
//We are going to simplify accessing
// g_form within the HTML by setting
// it as a $scope attribute
$scope.g_form = $;
// from here you can iterate over
// the url params;
var params = $window.location.href.split('?')[1];
var paramsToString = params.toString();
var paramsArr = paramsToString.split('&');{
var key = keyValue.split('=')[0];
var value = keyValue.split(key + '=').join('');
value = decodeURIComponent(value);
try {
var message = 'Setting ' + key + ' to ';
message += value + ' from url parameter.';
} catch (error) {
console.log('Error setting field', error);

This will try to set all the attributes on the form so in the following url;

The following will tried to be set;


P.S. Laurent Chicoine pointed out another way to do this for an individual variable. Thank you Laurent!

If you set the default value of the variable in question to this, then you can default it differently based on weather or not $sp exists.

javascript: (function(){
// Service Portal
// if $sp exists do this
return $sp.getParameter('var_short_description') || '';
} catch(e){
// UI16
// if $sp causes an error cause its not defined do this
return RP.getParameterValue('var_short_description');