27

I'd like to have a little easter egg button in the corner of a project site. When clicked, it just drops a string onto the current url and reloads the page.

So if I'm on: http://test.com/projects/view/134

The button is clicked

Page reload on: http://test.com/projects/view/134?ts=true

Not really sure how I might go about doing so though.

Fuego DeBassi
  • 2,967
  • 6
  • 29
  • 37

10 Answers10

33

try this code,

var separator = (window.location.href.indexOf("?")===-1)?"?":"&";
window.location.href = window.location.href + separator + "ts=true";

EDITS: to avoid duplicated parameter or very large string in your url, you need to replace the old param it already exists.

var url=window.location.href,
    separator = (url.indexOf("?")===-1)?"?":"&",
    newParam=separator + "ts=true";
    newUrl=url.replace(newParam,"");
    newUrl+=newParam;
    window.location.href =newUrl;
Community
  • 1
  • 1
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
  • 2
    but what if the URL contains a hash? – fabiangebert Apr 07 '14 at 08:12
  • @fabiangebert: `location.hash` will gives you the hash value. hope you can update the rest as you needed :) – Chamika Sandamal Apr 07 '14 at 09:09
  • 2
    This doesn't avoid the duplicate parameter as you assume the new param has the same value as the old one. But can work if you add a regex for the old one, such as `rparam = separator + "ts=", newParam = param + $(this).val(), regex = new RegExp(param+"[^\&]*"); newUrl = url.replace(regex, "");` – Antony D'Andrea Aug 31 '17 at 10:50
27

You can assign location.href to the value it currently has, plus your new querystring:

(edited to be friendly to existing querystrings)

$("#yourButtonId").click({
    var loc = location.href;
    if (loc.indexOf("?") === -1)
       loc += "?";
    else
       loc += "&";
    location.href = loc + "ts=true";
});

Or to be more succinct:

$("#yourButtonId").click({
    var loc = location.href;        
    loc += loc.indexOf("?") === -1 ? "?" : "&";

    location.href = loc + "ts=true";
});
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
16

Using:

Example:

var url = new URL("http://foo.bar/?x=1&y=2");

// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);

// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);

// Build result
url.toString();
Vianney Bajart
  • 7,490
  • 2
  • 13
  • 10
  • 1
    sadly not yet supported by all browsers https://caniuse.com/#feat=urlsearchparams – Iftah Nov 29 '17 at 10:27
  • @iftah according to the documentation `URL` can be accessed on non-supporting browsers through calling `window.URL`......Ex.(`new window.URL('url')`) https://developer.mozilla.org/en-US/docs/Web/API/URL – kingPuppy Jan 09 '20 at 00:52
5

Make full use of the location DOM API, and count in hash:

location.protocol + '//' + location.hostname + location.pathname + 
    (location.search ? location.search + '&a=b' : '?a=b') +
    location.hash;
Pikamander2
  • 7,332
  • 3
  • 48
  • 69
harttle
  • 88
  • 1
  • 12
  • 1
    I believe you missed location.hostname, should be `location.protocol + '//' + location.hostname + location.pathname + `... – ambidexterous Apr 04 '19 at 18:02
3

If you want to account for the potential existence of a hash "#" in the URL, proceed as follows:

var href = location.href;
var hasQuery = href.indexOf("?") + 1;
var hasHash = href.indexOf("#") + 1;
var appendix = (hasQuery ? "&" : "?") + "ts=true";
location.href = hasHash ? href.replace("#", appendix + "#") : href + appendix;
fabiangebert
  • 2,623
  • 2
  • 22
  • 25
3

I found the previous answers lacking and as such here is a method that better handles other parameters in current querystring

appendToQueryString = function (param, val) {
    var queryString = window.location.search.replace("?", "");
    var parameterListRaw = queryString == "" ? [] : queryString.split("&");
    var parameterList = {};
    for (var i = 0; i < parameterListRaw.length; i++) {
        var parameter = parameterListRaw[i].split("=");
        parameterList[parameter[0]] = parameter[1];
    }
    parameterList[param] = val;

    var newQueryString = "?";
    for (var item in parameterList) {
        if (parameterList.hasOwnProperty(item)) {
            newQueryString += item + "=" + parameterList[item] + "&";
        }
    }
    newQueryString = newQueryString.replace(/&$/, "");
    return location.origin + location.pathname + newQueryString;
}

You have to use location.href = appendToQueryString(ts, true) to actually reload the page.

Bobbzorzen
  • 101
  • 1
  • 13
  • So you split the whole query string, add one element and put it back together? Why would you do that instead of just appending the new parameter? makes no sense to me. – oshell Aug 17 '16 at 12:26
  • 2
    @HorstJahns to avoid params are being duplicated – Envil Dec 01 '16 at 09:04
2

Do you mean:


$(document).ready(function() {
    $("#yourButtonId").click(function() {
       var currentUrl = window.location.pathname + "?ts=true";
    });
});


Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1

See the documentation of the history API :

https://developer.mozilla.org/en-US/docs/Web/API/History_API

Example of usage:

var obj = { Title: title, Url: url }; history.pushState(obj, obj.Title, obj.Url);

0

An improvement from @Bobbzorzen answer, with ability to delete param by passing its name only:

function AlterQueryString(param, val) {
    var queryString = window.location.search.replace("?", "");
    var parameterListRaw = queryString == "" ? [] : queryString.split("&");
    var parameterList = {};
    for (var i = 0; i < parameterListRaw.length; i++) {
        var parameter = parameterListRaw[i].split("=");
        if (typeof val != 'undefined') {
            parameterList[parameter[0]] = parameter[1];
        } else if (param != parameter[0]) {
            parameterList[parameter[0]] = parameter[1];
        }
    }
    if (typeof val != 'undefined') {
        parameterList[param] = val;
    }

    var newQueryString = Object.keys(parameterList).length > 0 ? "?" : "";
    for (var item in parameterList) {
        if (parameterList.hasOwnProperty(item)) {
            newQueryString += item + "=" + parameterList[item] + "&";
        }
    }
    newQueryString = newQueryString.replace(/&$/, "");
    return location.origin + location.pathname + newQueryString;
}

gist: https://gist.github.com/envil/bc1832503bef55ffdabb0cde32bb06f1

Envil
  • 2,687
  • 1
  • 30
  • 42
0

HTML5 introduced the history.pushState(page, caption, replace_url) that should not reload your page. OR if you want to modify while page load you can do this.

var currentURL = www.getitsol.com;
window.location.replace(currentURL + "?data=" + data.result, "_self");
Malik Zahid
  • 593
  • 5
  • 13