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.

Warning

Do not try to just put JSON into the hash and then call eval(); otherwise, an attacker could just put malicious JavaScript code in the URL that is then run in the context of your site. This kind of attack is called Cross-Site Scripting (XSS) and is very dangerous. Therefore, always validate data before using it.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net