AJAX: How to Handle Bookmarks and Back Buttons
Pages: 1, 2, 3, 4, 5, 6
Example
Let's jump right in with a simple example.
First, any page that wishes to use the Really Simple History framework must include the dhtmlHistory.js script:
<!-- Load the Really Simple
History framework -->
<script type="text/javascript"
src="../../framework/dhtmlHistory.js">
</script>
DHTML History applications must also include a special file named blank.html in the same directory as their AJAX web page; this file is bundled with the Really Simple History framework and is needed by Internet Explorer. As a side note, RSH uses a hidden iframe to track and add history changes in Internet Explorer; this iframe requires that we point to a real location for the functionality to work correctly, hence blank.html.
The RSH framework creates a global object named
dhtmlHistory that is the entry point for manipulating
the browser's history. The first step in working with
dhtmlHistory is initializing the object after the page
has finished loading:
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
Next, developers use the dhtmlHistory.addListener()
method to subscribe to history change events. This method takes a
single JavaScript callback function that will receive two arguments
when a DHTML history change event occurs: the new location of the
page, and any optional history data that might be associated with
this event:
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
// subscribe to DHTML history change
// events
dhtmlHistory.addListener(historyChange);
The historyChange() method is straightforward, and
consists of a function that receives the newLocation
after a user has navigated to a new location, as well as any
optional historyData that was associated with the
event:
/** Our callback to receive history change
events. */
function historyChange(newLocation,
historyData) {
debug("A history change has occurred: "
+ "newLocation="+newLocation
+ ", historyData="+historyData,
true);
}
The debug() method used above is a utility function
defined in the example's source file, bundled with the full example
download. debug() simply prints a message into the web
page; the second Boolean argument, true in the code
above, controls whether all pre-existing messages are cleared
before the new debug message is printed.