Tag Archives: enable back button ajax

Fixing the Browser History (Back and Forward buttons) in AJAX Websites

BrowserHistory

Here is a small script that utilizes the JavaScript location.hash property to handle the broken back and forward browser buttons in AJAX websites.

For the demo we need is a simple AJAX callback function, the hash handling function and a couple of HTML pages to include in our one-page website via the XmlHttpRequest.

1. getcontent(file) – the argument of the function is the file that will be included to the page via AJAX. When the AJAX call is finished, we set the filename of the include as a hash in the address bar of the browser, i.e. http://localhost/History/index.html#page1.html.

function getcontent(file)
{
var xmlhttp;
var contentloader = $get('content');
var pagehash = file.split('Includes/');
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4)
{
contentloader.innerHTML = xmlhttp.responseText;
window.open('#' + pagehash[1], '_self');
}
else
{
$get('content').innerHTML = loading;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
$get('hash').value = pagehash[1];
}

2. checkHash() – We add this function to the site.init(). From now on it will listen for changes of the hash in the address bar of the browser on every 500 milliseconds, and will compare the value after the “#” sign with the value of the hidden input with id “hash” in the markup. If the two values differ (i.e. if the visitor has pressed the “back” or the “forward” button), checkHash() will load the include found after the hash sign.

function checkHash(){
 setInterval(function(e)
 {
  var gethash = document.location.hash;
  var pagehash = gethash.split('#')[1];
  var currenthash = $get('hash');
  if(pagehash != currenthash.value)
  {
   getcontent(includesdir + '/' + pagehash);
  }
 }, 500);
}

The history fixer works with all major browsers (Internet Explorer 7/8, FireFox 2/3, Opera 9/10 Beta, Chrome 1/2 and Safari 3/4). Supposedly it works in Internet Explorer 5.5/6 as well, but I haven’t tested it. The script is flexible enough and can be modified for database, xml or flat file asynchronous queries.

A fully working demo is availabe for download at this link. Make sure that you test it on a server (http://localhost/ or online), otherwise the AJAX requests will fail.