Skip to content

Instantly share code, notes, and snippets.

@thisnameissoclever
Created April 29, 2019 19:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thisnameissoclever/9f36b773f44cb70f0a896e6476b9c101 to your computer and use it in GitHub Desktop.
Save thisnameissoclever/9f36b773f44cb70f0a896e6476b9c101 to your computer and use it in GitHub Desktop.
//Note: Read from innermost, outward
getAllUrlParams(
decodeURIComponent(
getAllUrlParams( //Get all URL params. Since SN re-encodes everything it passes into page processors like "nav_to.do" for example, this will have one key-val pair.
(this.location.href ? this.location.href : window.location.href) //The document URL. Should work for SP, and desktop view.
)['uri']
)
);
var yourParamValue = getAllUrlParams(this.location.href)['YOUR_PARAM_NAME'];
/**
* Get the values of each URI param as properties of an object (name-value pairs).
* @param url
* @returns {{}}
* @example - In the URL www.google.com/page?urip=pickles&otheruriparam=bananas, you could use getAllUrlParams().urip to get "pickles".
*/
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i = 0; i < arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1, -1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof(a[1]) === 'undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}
/*
This script is part of a variable set which can be included on any catalog item, in order to enable this functionality.
When this script (or the "Set variables from URL" variable set) are included on a catalog item, then any variable(s) on that catalog item can be set on-load, by manipiulating the URL to the catalog item. You'll simply need to add a URI parameter called "sysparm_variables", and set the value of that parameter to a JSON-formatted string containing key/value pairs, where the key is a valid variable name, and the value is a valid value for that variable (for example, a sys_id in the case of a reference field).
The contents of the sysparm_variables object should be minimally encoded first as a JSON object, and secondly as a URL.
JSON encoding means you'll need to escape certain characters (such as backslashes) like so:
{"os_root":"C:\\windows"}
Notice how I've used two backaslashes after "C:" in the value above? This is the escape sequence for a single backslash.
URL encoding means that you'll need to escape certain other characters (such as spaces and ampersands) with URL-encoding sequences like so:
{"name":"Tim%20Woodruff"}
Notice how I've used "%20" in place of the space between my first and last name. This is because URLs do not accept spaces (though most browsers handle that for you automatically, which we'll discuss below)
Most modern programming languages (including JavaScript) also have methods for encoding and decoding URLs, so you can take any JSON-encoded string, run it through one of those functions, and use the result in your URL. *IF* you're URL-encoding something with backslashes in it, you'll have to *double-escape* them - they'll be escaped for the JSON encoding, and again for the URL encoding. For example:
encodeURIComponent('{"program_files_dir":"C:\\\\Program Files (x86)"}');
The above line of code will print the following string:
%7B%22program_files_dir%22%3A%22C%3A%5C%5CProgram%20Files%20(x86)%22%7D
If you look closely, you'll see the URL-encoded backslash character ("%5C") twice, not four times. This is because the "encodeURIComponent" function interpreted only two escaped backslashes, rather than four unescaped backslashes. That results in the correctly encoded version of the string "C:\Program Files (x86)", because when un-encoded, the two remaining backslashes will be interpreted as, again, a single *escaped* backslash. If you're not pre-URL-encoding the sysparm_variables object's value, then you only need to escape backslashes once, as mentioned above.
Most browsers will automatically encode URLs with invalid characters, but it's best to be safe and at least encode certain characters. You can manually URL-encode certain characters like spaces (%20) without having to worry about all of the extra bother of double-escaping stuff like backslashes.
Example usage: Simply append the following to the URL of the catalog item in either your service portal, or the classic UI:
&sysparm_variables={"catalog_variable_name":"variable%20value","var_name_2":"second%20variable%20value"}
This functionality should function identically for catalog items on both the classic, and the portal UI.
*/
function onLoad() {
var prop, propVal;
//get parameter from URL
var objVariables = getParameterValue('sysparm_variables');
console.debug('sysparm_variables URI parameter value: ' + objVariables);
if (!objVariables || objVariables == '' || objVariables.indexOf('{') != 0) {
//If variables is empty or not properly formatted, stop here.
console.debug('aborting due to a missing or problematic sysparm_variables URI parameter');
return;
}
objVariables = JSON.parse(objVariables);
console.debug('sysparm_variables URI parameter value: ' + JSON.stringify(objVariables));
for (prop in objVariables) {
if (!objVariables.hasOwnProperty(prop)) {
break;
}
propVal = objVariables[prop];
console.debug('Processing property ' + prop + ' with value ' + propVal);
if (g_form.hasField(prop)) {
console.debug('Setting variable ' + prop + ' to value ' + propVal);
g_form.setValue(prop, propVal);
} else {
console.warn('Variable ' + prop +
', specified in the sysparm_variables URI parameter, does not exist on this catalog item form.');
}
}
}
function getParameterValue(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
//Check if portal (gel=undefined) or classic UI, and get the HREF data appropriately in either case.
var hrefPath = (typeof gel == 'undefined') ? this.location.href : top.location.href;
var results = regex.exec(hrefPath);
console.debug('HREF: ' + hrefPath);
if (results == null) {
return "";
} else {
return unescape(results[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment