JavaScript: Change address bar URL when loading content with AJAX

There is a Mobile Optimized version of this page (AMP). Open Mobile Version.

Isn't it annoying when you have a website that uses AJAX to load each page of the site, but the URL in the address bar just stays as the URL to the entry page to the site?

Well it’s not just annoying its very user unfriendly too! Your users cannot hit F5 because that will load the “entry page”, they cannot bookmark because again it will only bookmark the “entry page” and the users browsing history does not appear in their history! All this basic functionality is lost for an otherwise great addition to your website.

we all agree AJAX is extremely useful in a website, it means we don't have to reload the WHOLE PAGE all the time and we can load only the data REQUIRED to be changed without wasting bandwidth.

If only the above problem wasn’t there, like an arrow to the knee… Stopping you from being that all famous adventurer…

Adding URL to history and address bar

Anyway I have a solution that will blow you away, in HTML5 we can now manipulate the browser history and the address bar (obviously with limitations such as you can only do it within the domain name the site is running on).

There's two parts to this solution, the first part is for changing the URL of the page and apply it to the browsers history. Once you have loaded the AJAX content into the page you can update the address bar using the following code:

//url is the var for the new URL we would normally be going to (if we wasnt AJAXING)
var url = "http://example.com/test.html";

//get current URL and remove domain name.
nohttp = url.replace("http://","").replace("https://","");
firstsla = nohttp.indexOf("/");
pathpos = url.indexOf(nohttp);
path = url.substring(pathpos + firstsla);

//Create a state object for tracking the history (this is passed back later)
var stateObj = { foo: 1000 + Math.random()*1001 };
history.pushState(stateObj, "ajax page loaded...", path);

The above code takes the new url and apply it to the users history, also applying it into the address bar. If the user presses F5 or bookmarks now, the url you passed is the url that will be used!

Loading a page added using the script above

A potentially confusing feature of the code above is that if the user goes to one of the history pages (or clicks back/forward), the browser will not refresh as normal and send a HTTP request to your site, instead it will fire a JavaScript event which you can capture and process with AJAX, to capture these events you need to capture the onpopstate:

window.onpopstate = function(event) {
	alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
	if (event.state != undefined) {
		loadPage(document.location.toString(),1);
	}
};

Place the code above at the top of your JavaScript file and it will fire whenever the above occurs, you can then send the URL to your AJAX function to load the content like you would normally with AJAX (in the example above I have a function called loadPage to load AJAX content from a url).

 

I hope this has been useful to you and helps you develop awesome AJAX powered websites, if you have any comment/suggestions or questions then please comment on this post and I will get back to you!

Don't forget to  credit me if this has helped you!

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips