Most of the answers here suggest adding a parameter to the URL, something like the following snippet or similar:
location.href = location.href + "¶meter=" + value;
This will work well for most cases.
However
This is not the right way to add a parameter to the url in my opinion.
Since the proposed approach does not check if the parameter is set in the URL, if it is not careful, you may have a very long URL with the same parameter that is repeated several times. i.e:
https:
at this point there are problems. The proposed approach can and will create a very long URL after updating several pages, which makes the URL invalid. Follow this link for more information on long URLs. What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){ var hash = {}; var parser = document.createElement('a'); parser.href = url; var parameters = parser.search.split(/\?|&/); for(var i=0; i < parameters.length; i++) { if(!parameters[i]) continue; var ary = parameters[i].split('='); hash[ary[0]] = ary[1]; } hash[param] = value; var list = []; Object.keys(hash).forEach(function (key) { list.push(key + '=' + hash[key]); }); parser.search = '?' + list.join('&'); return parser.href; }
Using this function, you will need to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
yeyo Jan 15 '15 at 18:59 2015-01-15 18:59
source share