Change Browser-URL Without Refreshing Page

Posted on November 27th, 2011 in category: Tips and Tricks

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:

Note

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+.

I’ll try to put together a complete tutorial on this in a while but as for now you can read more Mozilla’s developer pages. Or check it out in action while browsing Modernizrs source on GitHub.

Tip

If you prefer the hashtag solution while pushState gets more widely accepted you can check out my tutorial on Making SEO Friendly Ajax Easy.

Comments

  • Arun David, February 22nd, 2012

    Good tip.
    I’ve implemented a menubar with ajax data with changing the browser URL but without refreshing the page : http://tinywall.info/demos/html5-history-api/menu1.php

  • lasse, February 24th, 2012

    Nice tutorial Arun, works really nice, I might actually do one for ASP.NET if I get some spare time as it’s a cool and useful feature that I think will be quite widely used once it gets a bit wider browser support.

  • Anto, March 26th, 2012

    Hi ur script is working fine.but i’ve one issue when i refresh the page or click enter button THE RESOURCE NOT FOUND error was coming .HOw can i solve the issue

    window.history.pushState(“http://localhost:4961/TravGulf_Web/About_Us.aspx”,””,”http://localhost:4961/TravGulf_Web/About_Us”);

Trackbacks

No trackbacks are posted.

× five = 5