Back (And Forward) Button Problem in AJAX

Sunday, June 22, 2008

Last time I've wrote about how to solve the bookmark problem in AJAX, this time is how to handle the back(and forward) button problem. The issue remains the same, since the page's URL doesn't change(but the content does), the back and forward button will not work as expected. To solve this, here's a general method, merely a method since the implementation depends on how the system, the requirements, and the specs you use. 1. like the previous post, you must appy the information in location.hash when you load a page. 2. make sure that the browser stores the pages with the hash, if the browser doesn't then the back and forward button will not work. Mozilla derivatives browser do this, I don't know about Internet Explorer. To push the browser to save the page with hash history, you may use a hidden iframe with nothing in it, just to get an entry in browser's history. Here's the code

<iframe src="container.html" name="container" style="display: none" ></iframe>
Whenever the state changes on the page, the container frame should be forced to load again, with the state appended to the URL.
if (window.ActiveXObject) {
  window.frames["container"].window.location.search = "?" + escape(data);
}
We use only the ActiveXObject since this only necessary in IE, mozilla saves the pages with hash info in history automatically. Last, the container frame applies the state to the main page, again, this only needed in Internet Explorer, sice the browser back button change the contents of the iframe.
window.onload = function(){
 if(location.search.length>=2){
  var data = unescape(location.search.substring(1));
  top.applyState(state);
 }
}
Yes, it's a tiring process especially when there are many different AJAX requests on the page. But it's sure worth it. Hope this helps.

0 comments: