2

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

Richard
  • 1,414
  • 2
  • 16
  • 27

1 Answers1

4

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

Community
  • 1
  • 1
spacebean
  • 1,554
  • 1
  • 10
  • 13
  • Ah, that's true! I forgot about the history api! – bfavaretto Oct 16 '13 at 20:02
  • Interesting, can you show me an example of how to use this which would add to my current domain? For example, my current domain is "www.something.com/a-page-title" but I would like it to be "www.something.com/a-page-title/mobile" How is that done? Thank you – Richard Oct 16 '13 at 20:07
  • It's really just as simple as that line of code. I included a little more info and an example as well as a link to a more robust library if you need better browser support. Hope that does the trick for you. – spacebean Oct 16 '13 at 20:33
  • Yes, I tried that and it replaces anything after the the initial domain, for instance, www.something.com/original changed to www.something.com/lookiehere.html where as I would like it just to add to the URL, not replace so it would be www.something.com/originallookiehere.html Is that not possible with this? – Richard Oct 16 '13 at 20:37
  • Ah, yes, you can add to it, either hardcode the directory you want, or you could do it programtically, e.g. `history.pushState("", "", "/"+window.location.pathname.substr(1)+"lookiehere.html");` or `history.pushState("", "", "/"+window.location.pathname.substr(1)+"?this=this");` – spacebean Oct 16 '13 at 20:52