Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Solving the Bookmark Problem

var data = unescape(location.hash.substring(1));

One of the main issues with AJAX applications today is that it is not possible to bookmark a page. Since the contents of a page can change thanks to XMLHttpRequest calls, but the URL stays the same, bookmarking does not work.

There is, however, a workaround. Caveat: This workaround is just the shell of the code you have to write; the actual work you have to do (depending on your application) is how to persist data and then apply it back to the page.

The trick is to append data that identifies the current state of the page to the URL. Not in the form of a GET parameter (since this would cause a reload of the page), but in the hash:

http://server/file.html#info

The data denoted here with info must identify the current page status. The implementation details largely depend on how AJAX is used on the page.

Whenever the current state of the page changes, the page's hash (location.hash in JavaScript) must be updated. Then, the following code snippet reads in this information after the page is loaded. You have to implement the applyData() function that takes care of transforming the information in location.hash into actual content on the page.

window.onload = function() {
  if (location.hash.length >= 2) {
    var data = unescape(location.hash.substring(1));
    applyData(data);
  }
};

This, of course, increases the amount of work to be done, but your users benefit greatly from this convenient feature. Unfortunately, this approach does not work (yet) with Safari and Konqueror since they handle location.hash in a different way.

  • + Share This
  • 🔖 Save To Your Account