Normally when you change the URL in the address bar the browser reloads the page. This seems and is a normal behavior for your browser but it has also been an issue when using AJAX while trying to keep the back button working. So far people has been using the the hashtag to do this, but now a better way exists.
The new solution to this is HTML5 or more exactly the window.history.pushState function, which does exactly what it sounds like, it pushes a page state to your browser’s history.
Here’s an example of the pushState function:
window.history.pushState(object, "Title", "http://worldwidewhat.net/url");
This will change the URL in the address bar to “http://worldwidewhat.net/url” but it won’t redirect you to the page or even check if it actually exists. The function has three parameters:
- State object – This is an optional object you can associate with the state that is being pushed to the history.
- Title – This is a string that identifies the state, at the moment it’s ignored so you can enter anything you like here.
- URL – This is the URL that is set in the address bar and added to the browser history.
While the browser won’t request the new URL when calling pushState it will try to request it if the user reloads or restarts their browser it will try to request the URL, so you need to handle this on your server.
There’s also a replaceState function, which does the same as the pushState except for one thing, instead of adding a new entry to the browser’s history, it replaces the current entry. It looks like this:
window.history.replaceState(object, "Title", "http://worldwidewhat.net/url");
The pushState is a really interesting feature, It’s supported by Chrome, Firefox 4+, Safari 5+ and Opera 11.50+.
If you prefer the hashtag solution while pushState gets more widely accepted you can check out my tutorial on Making SEO Friendly Ajax Easy.