Richard
Richard

Reputation: 1474

With JavaScript or jQuery how to add a parameter to the URL after the page loads

Currently I'm using the following code to add a hashtag at the end of the URL after the page loads:

window.location.hash = 'mobile';

Alternatively, I need to add a parameter at the end of the URL, something like

"&location=mobile"

How would I go about doing something like that? Thank you

Upvotes: 2

Views: 165

Answers (1)

spacebean
spacebean

Reputation: 1554

See this for more information, but it can be done in most modern browsers now: Modify the URL without reloading the page

With HTML5:

window.history.pushState("object or string", "Title", "/new-url");

Unless you need the object when refering back to the history you can leave that blank, and the title doesn't actually currently change anything either so you probably don't need that. Essentially you just need the 3rd parameter most likely in your case. If you want to see it work, save this as an html file and run it (JSFiddle won't display it for some reason):

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

history.pushState("", "", "lookiehere.html");

</script>
</head>
<body>

  Look, I changed!


</body>
</html>

Or to keep the current uri and add to it:

    history.pushState("", "", "/"+window.location.pathname.substr(1)+"lookiehere.html");

Or, to keep just the folder structure but not any page url:

    var loc = window.location.pathname,
    dir = loc.substring(0, loc.lastIndexOf('/'));

history.pushState("", "", dir+"/whatever");

Edit: If you're worried about browser support/internet-explorer then History.js might be relevant to your interests: https://github.com/browserstate/history.js

Upvotes: 4

Related Questions