HTML5: How to change the browser URL without reload
One less known feature of HTML5 is the onpopstate event.
No longer do you need to use the hash(#) hack, if you want to add state in an AJAX powered application, and search engines bots will be able to crawl your pages and index them. You have to love HTML5.
How does this HTML5 goodness work?
It’s rather simple. You can open Chrome Developer Tools, navigate to the Sources tab and write:
window.history.pushState("object", "Title", "/new-path");
Once the code is executed, it will change the URL to domain-name.com/new-path. The “Title” option is used to describe the new state, and not change the title of the document as you’d expect. According to W3:
“Titles associated with session history entries need not have any relation with the current title of the Document. The title of a session history entry is intended to explain the state of the document at that point, so that the user can navigate the document’s history.”
If you want to change the document’s title to match your parameter, you’ll need to attach a handler to the onpopstate event.
window.history.back(); window.history.forward(); window.history.go(2);
If you want to replace a state you can write:
window.history.replaceState("object", "Title", "/new-path2");
This will change the URL of the page, but will not allow the user to click the back button to go back. This is due to the fact, that we replaced an already existing state, not added a new one.
There’s a catch!
If you are working long enough in the industry you have probably guessed it. While the latest versions of Chrome and Safari already have support for the HTML5 onpopstate feature and Firefox has announced support for it in the next version, it seems IE9 won’t bother supporting this feature according to this Wikipedia article (“Trident” is IE’s layout engine).
You can read the full W3 specification for more info.