2
Copyright (c) 2007 Brian Dillard and Brad Neuberg:
3
Brian Dillard | Project Lead | bdillard@pathf.com | http://blogs.pathf.com/agileajax/
4
Brad Neuberg | Original Project Creator | http://codinginparadise.org
6
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
7
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
8
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
9
so, subject to the following conditions:
11
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
13
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
15
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
16
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
dhtmlHistory: An object that provides history, history data, and bookmarking for DHTML and Ajax applications.
23
* the historyStorage object included in this file.
26
window.dhtmlHistory = {
28
/*Public: User-agent booleans*/
36
/*Public: Create the DHTML history infrastructure*/
37
create: function(options) {
40
options - object to store initialization parameters
41
options.debugMode - boolean that causes hidden form fields to be shown for development purposes.
42
options.toJSON - function to override default JSON stringifier
43
options.fromJSON - function to override default JSON parser
48
/*set user-agent flags*/
49
var UA = navigator.userAgent.toLowerCase();
50
var platform = navigator.platform.toLowerCase();
51
var vendor = navigator.vendor || "";
52
if (vendor === "KDE") {
53
this.isKonqueror = true;
54
this.isSupported = false;
55
} else if (typeof window.opera !== "undefined") {
57
this.isSupported = true;
58
} else if (typeof document.all !== "undefined") {
60
this.isSupported = true;
61
} else if (vendor.indexOf("Apple Computer, Inc.") > -1) {
63
this.isSupported = (platform.indexOf("mac") > -1);
64
} else if (UA.indexOf("gecko") != -1) {
66
this.isSupported = true;
69
/*Set up the historyStorage object; pass in init parameters*/
70
window.historyStorage.setup(options);
72
/*Execute browser-specific setup methods*/
75
} else if (this.isOpera) {
79
/*Get our initial location*/
80
var initialHash = this.getCurrentLocation();
82
/*Save it as our current location*/
83
this.currentLocation = initialHash;
85
/*Now that we have a hash, create IE-specific code*/
87
this.createIE(initialHash);
90
/*Add an unload listener for the page; this is needed for FF 1.5+ because this browser caches all dynamic updates to the
91
page, which can break some of our logic related to testing whether this is the first instance a page has loaded or whether
92
it is being pulled from the cache*/
94
var unloadHandler = function() {
95
that.firstLoad = null;
98
this.addEventListener(window,'unload',unloadHandler);
100
/*Determine if this is our first page load; for IE, we do this in this.iframeLoaded(), which is fired on pageload. We do it
101
there because we have no historyStorage at this point, which only exists after the page is finished loading in IE*/
103
/*The iframe will get loaded on page load, and we want to ignore this fact*/
104
this.ignoreLocationChange = true;
106
if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) {
107
/*This is our first page load, so ignore the location change and add our special history entry*/
108
this.ignoreLocationChange = true;
109
this.firstLoad = true;
110
historyStorage.put(this.PAGELOADEDSTRING, true);
112
/*This isn't our first page load, so indicate that we want to pay attention to this location change*/
113
this.ignoreLocationChange = false;
114
/*For browsers other than IE, fire a history change event; on IE, the event will be thrown automatically when its
115
hidden iframe reloads on page load. Unfortunately, we don't have any listeners yet; indicate that we want to fire
116
an event when a listener is added.*/
117
this.fireOnNewListener = true;
121
/*Other browsers can use a location handler that checks at regular intervals as their primary mechanism; we use it for IE as
122
well to handle an important edge case; see checkLocation() for details*/
123
var locationHandler = function() {
124
that.checkLocation();
126
setInterval(locationHandler, 100);
129
/*Public: Initialize our DHTML history. You must call this after the page is finished loading.*/
130
initialize: function() {
131
/*IE needs to be explicitly initialized. IE doesn't autofill form data until the page is finished loading, so we have to wait*/
133
/*If this is the first time this page has loaded*/
134
if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) {
135
/*For IE, we do this in initialize(); for other browsers, we do it in create()*/
136
this.fireOnNewListener = false;
137
this.firstLoad = true;
138
historyStorage.put(this.PAGELOADEDSTRING, true);
140
/*Else if this is a fake onload event*/
142
this.fireOnNewListener = true;
143
this.firstLoad = false;
148
/*Public: Adds a history change listener. Note that only one listener is supported at this time.*/
149
addListener: function(listener) {
150
this.listener = listener;
151
/*If the page was just loaded and we should not ignore it, fire an event to our new listener now*/
152
if (this.fireOnNewListener) {
153
this.fireHistoryEvent(this.currentLocation);
154
this.fireOnNewListener = false;
158
/*Public: Generic utility function for attaching events*/
159
addEventListener: function(o,e,l) {
160
if (o.addEventListener) {
161
o.addEventListener(e,l,false);
162
} else if (o.attachEvent) {
163
o.attachEvent('on'+e,function() {
169
/*Public: Add a history point.*/
170
add: function(newLocation, historyData) {
174
/*Remove any leading hash symbols on newLocation*/
175
newLocation = this.removeHash(newLocation);
177
/*Store the history data into history storage*/
178
historyStorage.put(newLocation, historyData);
180
/*Save this as our current location*/
181
this.currentLocation = newLocation;
183
/*Change the browser location*/
184
window.location.hash = newLocation;
186
/*Save this to the Safari form field*/
187
this.putSafariState(newLocation);
191
/*Most browsers require that we wait a certain amount of time before changing the location, such
192
as 200 MS; rather than forcing external callers to use window.setTimeout to account for this,
193
we internally handle it by putting requests in a queue.*/
195
var addImpl = function() {
197
/*Indicate that the current wait time is now less*/
198
if (that.currentWaitTime > 0) {
199
that.currentWaitTime = that.currentWaitTime - that.waitTime;
202
/*Remove any leading hash symbols on newLocation*/
203
newLocation = that.removeHash(newLocation);
205
/*IE has a strange bug; if the newLocation is the same as _any_ preexisting id in the
206
document, then the history action gets recorded twice; throw a programmer exception if
207
there is an element with this ID*/
208
if (document.getElementById(newLocation) && that.debugMode) {
209
var e = "Exception: History locations can not have the same value as _any_ IDs that might be in the document,"
210
+ " due to a bug in IE; please ask the developer to choose a history location that does not match any HTML"
211
+ " IDs in this document. The following ID is already taken and cannot be a location: " + newLocation;
215
/*Store the history data into history storage*/
216
historyStorage.put(newLocation, historyData);
218
/*Indicate to the browser to ignore this upcomming location change since we're making it programmatically*/
219
that.ignoreLocationChange = true;
221
/*Indicate to IE that this is an atomic location change block*/
222
that.ieAtomicLocationChange = true;
224
/*Save this as our current location*/
225
that.currentLocation = newLocation;
227
/*Change the browser location*/
228
window.location.hash = newLocation;
230
/*Change the hidden iframe's location if on IE*/
232
that.iframe.src = "blank.html?" + newLocation;
235
/*End of atomic location change block for IE*/
236
that.ieAtomicLocationChange = false;
239
/*Now queue up this add request*/
240
window.setTimeout(addImpl, this.currentWaitTime);
242
/*Indicate that the next request will have to wait for awhile*/
243
this.currentWaitTime = this.currentWaitTime + this.waitTime;
248
isFirstLoad: function() {
249
return this.firstLoad;
253
getVersion: function() {
257
/*Get browser's current hash location; for Safari, read value from a hidden form field*/
260
getCurrentLocation: function() {
261
var r = (this.isSafari
262
? this.getSafariState()
263
: this.getCurrentHash()
268
/*Public: Manually parse the current url for a hash; tip of the hat to YUI*/
269
getCurrentHash: function() {
270
var r = window.location.href;
271
var i = r.indexOf("#");
278
/*- - - - - - - - - - - -*/
280
/*Private: Constant for our own internal history event called when the page is loaded*/
281
PAGELOADEDSTRING: "DhtmlHistory_pageLoaded",
283
/*Private: Our history change listener.*/
286
/*Private: MS to wait between add requests - will be reset for certain browsers*/
289
/*Private: MS before an add request can execute*/
292
/*Private: Our current hash location, without the "#" symbol.*/
293
currentLocation: null,
295
/*Private: Hidden iframe used to IE to detect history changes*/
298
/*Private: Flags and DOM references used only by Safari*/
299
safariHistoryStartPoint: null,
303
/*Private: Flag used to keep checkLocation() from doing anything when it discovers location changes we've made ourselves
304
programmatically with the add() method. Basically, add() sets this to true. When checkLocation() discovers it's true,
305
it refrains from firing our listener, then resets the flag to false for next cycle. That way, our listener only gets fired on
306
history change events triggered by the user via back/forward buttons and manual hash changes. This flag also helps us set up
307
IE's special iframe-based method of handling history changes.*/
308
ignoreLocationChange: null,
310
/*Private: A flag that indicates that we should fire a history change event when we are ready, i.e. after we are initialized and
311
we have a history change listener. This is needed due to an edge case in browsers other than IE; if you leave a page entirely
312
then return, we must fire this as a history change event. Unfortunately, we have lost all references to listeners from earlier,
313
because JavaScript clears out.*/
314
fireOnNewListener: null,
316
/*Private: A variable that indicates whether this is the first time this page has been loaded. If you go to a web page, leave it
317
for another one, and then return, the page's onload listener fires again. We need a way to differentiate between the first page
318
load and subsequent ones. This variable works hand in hand with the pageLoaded variable we store into historyStorage.*/
321
/*Private: A variable to handle an important edge case in IE. In IE, if a user manually types an address into their browser's
322
location bar, we must intercept this by calling checkLocation() at regular intervals. However, if we are programmatically
323
changing the location bar ourselves using the add() method, we need to ignore these changes in checkLocation(). Unfortunately,
324
these changes take several lines of code to complete, so for the duration of those lines of code, we set this variable to true.
325
That signals to checkLocation() to ignore the change-in-progress. Once we're done with our chunk of location-change code in
326
add(), we set this back to false. We'll do the same thing when capturing user-entered address changes in checkLocation itself.*/
327
ieAtomicLocationChange: null,
329
/*Private: Create IE-specific DOM nodes and overrides*/
330
createIE: function(initialHash) {
331
/*write out a hidden iframe for IE and set the amount of time to wait between add() requests*/
332
this.waitTime = 400;/*IE needs longer between history updates*/
333
var styles = (historyStorage.debugMode
334
? 'width: 800px;height:80px;border:1px solid black;'
335
: historyStorage.hideStyles
337
var iframeID = "rshHistoryFrame";
338
var iframeHTML = '<iframe frameborder="0" id="' + iframeID + '" style="' + styles + '" src="blank.html?' + initialHash + '"></iframe>';
339
document.write(iframeHTML);
340
this.iframe = document.getElementById(iframeID);
343
/*Private: Create Opera-specific DOM nodes and overrides*/
344
createOpera: function() {
345
this.waitTime = 400;/*Opera needs longer between history updates*/
346
var imgHTML = '<img src="javascript:location.href=\'javascript:dhtmlHistory.checkLocation();\';" style="' + historyStorage.hideStyles + '" />';
347
document.write(imgHTML);
350
/*Private: Create Safari-specific DOM nodes and overrides*/
351
createSafari: function() {
352
var formID = "rshSafariForm";
353
var stackID = "rshSafariStack";
354
var lengthID = "rshSafariLength";
355
var formStyles = historyStorage.debugMode ? historyStorage.showStyles : historyStorage.hideStyles;
356
var inputStyles = (historyStorage.debugMode
357
? 'width:800px;height:20px;border:1px solid black;margin:0;padding:0;'
358
: historyStorage.hideStyles
360
var safariHTML = '<form id="' + formID + '" style="' + formStyles + '">'
361
+ '<input type="text" style="' + inputStyles + '" id="' + stackID + '" value="[]"/>'
362
+ '<input type="text" style="' + inputStyles + '" id="' + lengthID + '" value=""/>'
364
document.write(safariHTML);
365
this.safariStack = document.getElementById(stackID);
366
this.safariLength = document.getElementById(lengthID);
367
if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) {
368
this.safariHistoryStartPoint = history.length;
369
this.safariLength.value = this.safariHistoryStartPoint;
371
this.safariHistoryStartPoint = this.safariLength.value;
375
/*Private: Safari method to read the history stack from a hidden form field*/
376
getSafariStack: function() {
377
var r = this.safariStack.value;
378
return historyStorage.fromJSON(r);
381
/*Private: Safari method to read from the history stack*/
382
getSafariState: function() {
383
var stack = this.getSafariStack();
384
var state = stack[history.length - this.safariHistoryStartPoint - 1];
387
/*Private: Safari method to write the history stack to a hidden form field*/
388
putSafariState: function(newLocation) {
389
var stack = this.getSafariStack();
390
stack[history.length - this.safariHistoryStartPoint] = newLocation;
391
this.safariStack.value = historyStorage.toJSON(stack);
394
/*Private: Notify the listener of new history changes.*/
395
fireHistoryEvent: function(newHash) {
396
/*extract the value from our history storage for this hash*/
397
var historyData = historyStorage.get(newHash);
398
/*call our listener*/
399
this.listener.call(null, newHash, historyData);
402
/*Private: See if the browser has changed location. This is the primary history mechanism for Firefox. For IE, we use this to
403
handle an important edge case: if a user manually types in a new hash value into their IE location bar and press enter, we want to
404
to intercept this and notify any history listener.*/
405
checkLocation: function() {
407
/*Ignore any location changes that we made ourselves for browsers other than IE*/
408
if (!this.isIE && this.ignoreLocationChange) {
409
this.ignoreLocationChange = false;
413
/*If we are dealing with IE and we are in the middle of making a location change from an iframe, ignore it*/
414
if (!this.isIE && this.ieAtomicLocationChange) {
418
/*Get hash location*/
419
var hash = this.getCurrentLocation();
421
/*Do nothing if there's been no change*/
422
if (hash == this.currentLocation) {
426
/*In IE, users manually entering locations into the browser; we do this by comparing the browser's location against the
427
iframe's location; if they differ, we are dealing with a manual event and need to place it inside our history, otherwise
429
this.ieAtomicLocationChange = true;
431
if (this.isIE && this.getIframeHash() != hash) {
432
this.iframe.src = "blank.html?" + hash;
434
else if (this.isIE) {
435
/*the iframe is unchanged*/
439
/*Save this new location*/
440
this.currentLocation = hash;
442
this.ieAtomicLocationChange = false;
444
/*Notify listeners of the change*/
445
this.fireHistoryEvent(hash);
448
/*Private: Get the current location of IE's hidden iframe.*/
449
getIframeHash: function() {
450
var doc = this.iframe.contentWindow.document;
451
var hash = String(doc.location.search);
452
if (hash.length == 1 && hash.charAt(0) == "?") {
455
else if (hash.length >= 2 && hash.charAt(0) == "?") {
456
hash = hash.substring(1);
461
/*Private: Remove any leading hash that might be on a location.*/
462
removeHash: function(hashValue) {
464
if (hashValue === null || hashValue === undefined) {
467
else if (hashValue === "") {
470
else if (hashValue.length == 1 && hashValue.charAt(0) == "#") {
473
else if (hashValue.length > 1 && hashValue.charAt(0) == "#") {
474
r = hashValue.substring(1);
482
/*Private: For IE, tell when the hidden iframe has finished loading.*/
483
iframeLoaded: function(newLocation) {
484
/*ignore any location changes that we made ourselves*/
485
if (this.ignoreLocationChange) {
486
this.ignoreLocationChange = false;
490
/*Get the new location*/
491
var hash = String(newLocation.search);
492
if (hash.length == 1 && hash.charAt(0) == "?") {
495
else if (hash.length >= 2 && hash.charAt(0) == "?") {
496
hash = hash.substring(1);
498
/*Keep the browser location bar in sync with the iframe hash*/
499
window.location.hash = hash;
501
/*Notify listeners of the change*/
502
this.fireHistoryEvent(hash);
508
historyStorage: An object that uses a hidden form to store history state across page loads. The mechanism for doing so relies on
509
the fact that browsers save the text in form data for the life of the browser session, which means the text is still there when
510
the user navigates back to the page. This object can be used independently of the dhtmlHistory object for caching of Ajax
514
* json2007.js (included in a separate file) or alternate JSON methods passed in through an options bundle.
516
window.historyStorage = {
518
/*Public: Set up our historyStorage object for use by dhtmlHistory or other objects*/
519
setup: function(options) {
522
options - object to store initialization parameters - passed in from dhtmlHistory or directly into historyStorage
523
options.debugMode - boolean that causes hidden form fields to be shown for development purposes.
524
options.toJSON - function to override default JSON stringifier
525
options.fromJSON - function to override default JSON parser
528
/*process init parameters*/
529
if (typeof options !== "undefined") {
530
if (options.debugMode) {
531
this.debugMode = options.debugMode;
533
if (options.toJSON) {
534
this.toJSON = options.toJSON;
536
if (options.fromJSON) {
537
this.fromJSON = options.fromJSON;
541
/*write a hidden form and textarea into the page; we'll stow our history stack here*/
542
var formID = "rshStorageForm";
543
var textareaID = "rshStorageField";
544
var formStyles = this.debugMode ? historyStorage.showStyles : historyStorage.hideStyles;
545
var textareaStyles = (historyStorage.debugMode
546
? 'width: 800px;height:80px;border:1px solid black;'
547
: historyStorage.hideStyles
549
var textareaHTML = '<form id="' + formID + '" style="' + formStyles + '">'
550
+ '<textarea id="' + textareaID + '" style="' + textareaStyles + '"></textarea>'
552
document.write(textareaHTML);
553
this.storageField = document.getElementById(textareaID);
554
if (typeof window.opera !== "undefined") {
555
this.storageField.focus();/*Opera needs to focus this element before persisting values in it*/
560
put: function(key, value) {
561
this.assertValidKey(key);
562
/*if we already have a value for this, remove the value before adding the new one*/
563
if (this.hasKey(key)) {
566
/*store this new key*/
567
this.storageHash[key] = value;
568
/*save and serialize the hashtable into the form*/
569
this.saveHashTable();
574
this.assertValidKey(key);
575
/*make sure the hash table has been loaded from the form*/
576
this.loadHashTable();
577
var value = this.storageHash[key];
578
if (value === undefined) {
585
remove: function(key) {
586
this.assertValidKey(key);
587
/*make sure the hash table has been loaded from the form*/
588
this.loadHashTable();
590
delete this.storageHash[key];
591
/*serialize and save the hash table into the form*/
592
this.saveHashTable();
595
/*Public: Clears out all saved data.*/
597
this.storageField.value = "";
598
this.storageHash = {};
602
hasKey: function(key) {
603
this.assertValidKey(key);
604
/*make sure the hash table has been loaded from the form*/
605
this.loadHashTable();
606
return (typeof this.storageHash[key] !== "undefined");
610
isValidKey: function(key) {
611
return (typeof key === "string");
614
/*Public - CSS strings utilized by both objects to hide or show behind-the-scenes DOM elements*/
615
showStyles: 'border:0;margin:0;padding:0;',
616
hideStyles: 'left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;',
618
/*Public - debug mode flag*/
621
/*- - - - - - - - - - - -*/
623
/*Private: Our hash of key name/values.*/
626
/*Private: If true, we have loaded our hash table out of the storage form.*/
629
/*Private: DOM reference to our history field*/
632
/*Private: Assert that a key is valid; throw an exception if it not.*/
633
assertValidKey: function(key) {
634
var isValid = this.isValidKey(key);
635
if (!isValid && this.debugMode) {
636
throw new Error("Please provide a valid key for window.historyStorage. Invalid key = " + key + ".");
640
/*Private: Load the hash table up from the form.*/
641
loadHashTable: function() {
642
if (!this.hashLoaded) {
643
var serializedHashTable = this.storageField.value;
644
if (serializedHashTable !== "" && serializedHashTable !== null) {
645
this.storageHash = this.fromJSON(serializedHashTable);
646
this.hashLoaded = true;
650
/*Private: Save the hash table into the form.*/
651
saveHashTable: function() {
652
this.loadHashTable();
653
var serializedHashTable = this.toJSON(this.storageHash);
654
this.storageField.value = serializedHashTable;
656
/*Private: Bridges for our JSON implementations - both rely on 2007 JSON.org library - can be overridden by options bundle*/
657
toJSON: function(o) {
658
return o.toJSONString();
660
fromJSON: function(s) {
661
return s.parseJSON();