Append to URL and refresh page Append to URL and refresh page javascript javascript

Append to URL and refresh page


this should work (not tested!)

var url = window.location.href;    if (url.indexOf('?') > -1){   url += '&param=1'}else{   url += '?param=1'}window.location.href = url;


Shorter than the accepted answer, doing the same, but keeping it simple:

window.location.search += '&param=42';

We don't have to alter the entire url, just the query string, known as the search attribute of location.

When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.


Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:

location.href = location.href + "&parameter=" + value;

This will work quite well for the majority of the cases.

However

That's not the correct way to append a parameter to a URL in my opinion.

Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:

https://stackoverflow.com/?&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1

at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL 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;}

With this function one just will have to do the following:

location.href = URL_add_parameter(location.href, 'param', 'value');