2 * Originally based of this code... - refactored for Roo...
5 * @author Benjamin Arthur Lupton <contact@balupton.com>
6 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
7 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
13 // ====================================================================
19 * How long should the interval be before hashchange checks
21 thishashChangeInterval : 100,
25 * How long should the interval be before safari poll checks
27 safariPollInterval : 500,
30 * History.options.doubleCheckInterval
31 * How long should the interval be before we perform a double check
33 doubleCheckInterval : 500,
36 * History.options.disableSuid
37 * Force this.not to append suid
42 * History.options.storeInterval
43 * How long should we wait between store calls
48 * History.options.busyDelay
49 * How long should we wait between busy events
54 * History.options.debug
55 * If true will enable debug messages to be logged
60 * History.options.initialTitle
61 * What is the title of the initial state
66 * History.options.html4Mode
67 * If true, will force HTMl4 mode (hashtags)
72 * History.options.delayInit
73 * Want to override default options and call init manually.
79 * Which bugs are present
83 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
84 * https://bugs.webkit.org/show_bug.cgi?id=56249
89 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
90 * https://bugs.webkit.org/show_bug.cgi?id=42940
95 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
100 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
105 // ========================================================================
111 sessionStorage : false, // sessionStorage
113 intervalList : false, // array normally.
116 // Initialise History
117 init : function(options){
119 initialTitle : window.document.title,
121 Roo.apply(this,options)
123 // Check Load Status of Adapter
124 //if ( typeof this.Adapter === 'undefined' ) {
128 // Check Load Status of Core
129 if ( typeof this.initCore !== 'undefined' ) {
133 // Check Load Status of HTML4 Support
134 if ( typeof this.initHtml4 !== 'undefined' ) {
141 * Is History enabled?
143 this.enabled = !this.emulated.pushState;
152 // ========================================================================
156 initCore : function(options){
158 this.intervalList = [];
162 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
163 this.sessionStorage.setItem('TEST', '1');
164 this.sessionStorage.removeItem('TEST');
166 this.sessionStorage = false;
170 if ( typeof this.initCore.initialized !== 'undefined' ) {
175 this.initCore.initialized = true;
183 * History.clearAllIntervals
184 * Clears all setInterval instances.
186 clearAllIntervals: function()
188 var i, il = this.intervalList;
189 if (typeof il !== "undefined" && il !== null) {
190 for (i = 0; i < il.length; i++) {
191 clearInterval(il[i]);
193 this.intervalList = null;
198 // ====================================================================
202 * History.debugLog(message,...)
203 * Logs the passed arguments if debug enabled
205 debugLog : function()
207 if ( (this.debug||false) ) {
208 Roo.log.apply(History,arguments);
214 // ====================================================================
218 * History.getInternetExplorerMajorVersion()
219 * Get's the major version of Internet Explorer
221 * @license Public Domain
222 * @author Benjamin Arthur Lupton <contact@balupton.com>
223 * @author James Padolsey <https://gist.github.com/527683>
225 getInternetExplorerMajorVersion : function(){
226 var result = this.getInternetExplorerMajorVersion.cached =
227 (typeof this.getInternetExplorerMajorVersion.cached !== 'undefined')
228 ? this.getInternetExplorerMajorVersion.cached
231 div = window.document.createElement('div'),
232 all = div.getElementsByTagName('i');
233 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
234 return (v > 4) ? v : false;
241 * isInternetExplorer()
242 * Are we using Internet Explorer?
244 * @license Public Domain
245 * @author Benjamin Arthur Lupton <contact@balupton.com>
247 isInternetExplorer = function(){
249 this.isInternetExplorer.cached =
250 (typeof this.isInternetExplorer.cached !== 'undefined')
251 ? this.isInternetExplorer.cached
252 : Boolean(this.getInternetExplorerMajorVersion())
258 * Which features require emulating?
266 initEmulated : function()
270 if (this.html4Mode) {
276 this.emulated.pushState = !Boolean(
277 window.history && window.history.pushState && window.history.replaceState
279 (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(window.navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
280 || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(window.navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
283 this.emulated.hashChange = Boolean(
284 !(('onhashchange' in window) || ('onhashchange' in window.document))
286 (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
294 * History.isEmptyObject(obj)
295 * Checks to see if the Object is Empty
296 * @param {Object} obj
299 History.isEmptyObject = function(obj) {
300 for ( var name in obj ) {
301 if ( obj.hasOwnProperty(name) ) {
309 * History.cloneObject(obj)
310 * Clones a object and eliminate all references to the original contexts
311 * @param {Object} obj
314 History.cloneObject = function(obj) {
317 hash = JSON.stringify(obj);
318 newObj = JSON.parse(hash);
327 // ====================================================================
331 * History.getRootUrl()
332 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
333 * @return {String} rootUrl
335 History.getRootUrl = function(){
337 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
338 if ( window.document.location.port||false ) {
339 rootUrl += ':'+window.document.location.port;
348 * History.getBaseHref()
349 * Fetches the `href` attribute of the `<base href="...">` element if it exists
350 * @return {String} baseHref
352 History.getBaseHref = function(){
355 baseElements = window.document.getElementsByTagName('base'),
359 // Test for Base Element
360 if ( baseElements.length === 1 ) {
361 // Prepare for Base Element
362 baseElement = baseElements[0];
363 baseHref = baseElement.href.replace(/[^\/]+$/,'');
366 // Adjust trailing slash
367 baseHref = baseHref.replace(/\/+$/,'');
368 if ( baseHref ) baseHref += '/';
375 * History.getBaseUrl()
376 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
377 * @return {String} baseUrl
379 History.getBaseUrl = function(){
381 var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
388 * History.getPageUrl()
389 * Fetches the URL of the current page
390 * @return {String} pageUrl
392 History.getPageUrl = function(){
395 State = History.getState(false,false),
396 stateUrl = (State||{}).url||History.getLocationHref(),
400 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
401 return (/\./).test(part) ? part : part+'/';
409 * History.getBasePageUrl()
410 * Fetches the Url of the directory of the current page
411 * @return {String} basePageUrl
413 History.getBasePageUrl = function(){
415 var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
416 return (/[^\/]$/).test(part) ? '' : part;
417 }).replace(/\/+$/,'')+'/';
424 * History.getFullUrl(url)
425 * Ensures that we have an absolute URL and not a relative URL
426 * @param {string} url
427 * @param {Boolean} allowBaseHref
428 * @return {string} fullUrl
430 History.getFullUrl = function(url,allowBaseHref){
432 var fullUrl = url, firstChar = url.substring(0,1);
433 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
436 if ( /[a-z]+\:\/\//.test(url) ) {
439 else if ( firstChar === '/' ) {
441 fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
443 else if ( firstChar === '#' ) {
445 fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
447 else if ( firstChar === '?' ) {
449 fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
453 if ( allowBaseHref ) {
454 fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
456 fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
458 // We have an if condition above as we do not want hashes
459 // which are relative to the baseHref in our URLs
460 // as if the baseHref changes, then all our bookmarks
461 // would now point to different locations
462 // whereas the basePageUrl will always stay the same
466 return fullUrl.replace(/\#$/,'');
470 * History.getShortUrl(url)
471 * Ensures that we have a relative URL and not a absolute URL
472 * @param {string} url
473 * @return {string} url
475 History.getShortUrl = function(url){
477 var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
480 if ( History.emulated.pushState ) {
481 // We are in a if statement as when pushState is not emulated
482 // The actual url these short urls are relative to can change
483 // So within the same session, we the url may end up somewhere different
484 shortUrl = shortUrl.replace(baseUrl,'');
488 shortUrl = shortUrl.replace(rootUrl,'/');
490 // Ensure we can still detect it as a state
491 if ( History.isTraditionalAnchor(shortUrl) ) {
492 shortUrl = './'+shortUrl;
496 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
503 * History.getLocationHref(document)
504 * Returns a normalized version of document.location.href
505 * accounting for browser inconsistencies, etc.
507 * This URL will be URI-encoded and will include the hash
509 * @param {object} document
510 * @return {string} url
512 History.getLocationHref = function(doc) {
513 doc = doc || window.document;
515 // most of the time, this will be true
516 if (doc.URL === doc.location.href)
517 return doc.location.href;
519 // some versions of webkit URI-decode document.location.href
520 // but they leave document.URL in an encoded state
521 if (doc.location.href === decodeURIComponent(doc.URL))
524 // FF 3.6 only updates document.URL when a page is reloaded
525 // document.location.href is updated correctly
526 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
527 return doc.location.href;
529 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
530 return doc.location.href;
532 return doc.URL || doc.location.href;
536 // ====================================================================
541 * The store for all session specific data
547 * 1-1: State ID to State Object
549 History.idToState = History.idToState||{};
553 * 1-1: State String to State ID
555 History.stateToId = History.stateToId||{};
559 * 1-1: State URL to State ID
561 History.urlToId = History.urlToId||{};
564 * History.storedStates
565 * Store the states in an array
567 History.storedStates = History.storedStates||[];
570 * History.savedStates
571 * Saved the states in an array
573 History.savedStates = History.savedStates||[];
576 * History.noramlizeStore()
577 * Noramlize the store by adding necessary values
579 History.normalizeStore = function(){
580 History.store.idToState = History.store.idToState||{};
581 History.store.urlToId = History.store.urlToId||{};
582 History.store.stateToId = History.store.stateToId||{};
587 * Get an object containing the data, title and url of the current state
588 * @param {Boolean} friendly
589 * @param {Boolean} create
590 * @return {Object} State
592 History.getState = function(friendly,create){
594 if ( typeof friendly === 'undefined' ) { friendly = true; }
595 if ( typeof create === 'undefined' ) { create = true; }
598 var State = History.getLastSavedState();
601 if ( !State && create ) {
602 State = History.createStateObject();
607 State = History.cloneObject(State);
608 State.url = State.cleanUrl||State.url;
616 * History.getIdByState(State)
617 * Gets a ID for a State
618 * @param {State} newState
619 * @return {String} id
621 History.getIdByState = function(newState){
624 var id = History.extractId(newState.url),
628 // Find ID via State String
629 str = History.getStateString(newState);
630 if ( typeof History.stateToId[str] !== 'undefined' ) {
631 id = History.stateToId[str];
633 else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
634 id = History.store.stateToId[str];
639 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
640 if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
645 // Apply the new State to the ID
646 History.stateToId[str] = id;
647 History.idToState[id] = newState;
656 * History.normalizeState(State)
657 * Expands a State Object
658 * @param {object} State
661 History.normalizeState = function(oldState){
663 var newState, dataNotEmpty;
666 if ( !oldState || (typeof oldState !== 'object') ) {
671 if ( typeof oldState.normalized !== 'undefined' ) {
676 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
680 // ----------------------------------------------------------------
684 newState.normalized = true;
685 newState.title = oldState.title||'';
686 newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
687 newState.hash = History.getShortUrl(newState.url);
688 newState.data = History.cloneObject(oldState.data);
691 newState.id = History.getIdByState(newState);
693 // ----------------------------------------------------------------
696 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
697 newState.url = newState.cleanUrl;
699 // Check to see if we have more than just a url
700 dataNotEmpty = !History.isEmptyObject(newState.data);
703 if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
705 newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
706 if ( !/\?/.test(newState.hash) ) {
707 newState.hash += '?';
709 newState.hash += '&_suid='+newState.id;
712 // Create the Hashed URL
713 newState.hashedUrl = History.getFullUrl(newState.hash);
715 // ----------------------------------------------------------------
717 // Update the URL if we have a duplicate
718 if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
719 newState.url = newState.hashedUrl;
722 // ----------------------------------------------------------------
729 * History.createStateObject(data,title,url)
730 * Creates a object based on the data, title and url state params
731 * @param {object} data
732 * @param {string} title
733 * @param {string} url
736 History.createStateObject = function(data,title,url){
745 State = History.normalizeState(State);
752 * History.getStateById(id)
753 * Get a state by it's UID
756 History.getStateById = function(id){
761 var State = History.idToState[id] || History.store.idToState[id] || undefined;
768 * Get a State's String
769 * @param {State} passedState
771 History.getStateString = function(passedState){
773 var State, cleanedState, str;
776 State = History.normalizeState(passedState);
781 title: passedState.title,
786 str = JSON.stringify(cleanedState);
794 * @param {State} passedState
795 * @return {String} id
797 History.getStateId = function(passedState){
802 State = History.normalizeState(passedState);
812 * History.getHashByState(State)
813 * Creates a Hash for the State Object
814 * @param {State} passedState
815 * @return {String} hash
817 History.getHashByState = function(passedState){
822 State = History.normalizeState(passedState);
832 * History.extractId(url_or_hash)
833 * Get a State ID by it's URL or Hash
834 * @param {string} url_or_hash
835 * @return {string} id
837 History.extractId = function ( url_or_hash ) {
839 var id,parts,url, tmp;
843 // If the URL has a #, use the id from before the #
844 if (url_or_hash.indexOf('#') != -1)
846 tmp = url_or_hash.split("#")[0];
853 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
854 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
855 id = parts ? String(parts[2]||'') : '';
862 * History.isTraditionalAnchor
863 * Checks to see if the url is a traditional anchor or not
864 * @param {String} url_or_hash
867 History.isTraditionalAnchor = function(url_or_hash){
869 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
872 return isTraditional;
876 * History.extractState
877 * Get a State by it's URL or Hash
878 * @param {String} url_or_hash
879 * @return {State|null}
881 History.extractState = function(url_or_hash,create){
883 var State = null, id, url;
884 create = create||false;
887 id = History.extractId(url_or_hash);
889 State = History.getStateById(id);
892 // Fetch SUID returned no State
895 url = History.getFullUrl(url_or_hash);
898 id = History.getIdByUrl(url)||false;
900 State = History.getStateById(id);
904 if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
905 State = History.createStateObject(null,null,url);
914 * History.getIdByUrl()
915 * Get a State ID by a State URL
917 History.getIdByUrl = function(url){
919 var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
926 * History.getLastSavedState()
927 * Get an object containing the data, title and url of the current state
928 * @return {Object} State
930 History.getLastSavedState = function(){
931 return History.savedStates[History.savedStates.length-1]||undefined;
935 * History.getLastStoredState()
936 * Get an object containing the data, title and url of the current state
937 * @return {Object} State
939 History.getLastStoredState = function(){
940 return History.storedStates[History.storedStates.length-1]||undefined;
944 * History.hasUrlDuplicate
945 * Checks if a Url will have a url conflict
946 * @param {Object} newState
947 * @return {Boolean} hasDuplicate
949 History.hasUrlDuplicate = function(newState) {
951 var hasDuplicate = false,
955 oldState = History.extractState(newState.url);
958 hasDuplicate = oldState && oldState.id !== newState.id;
967 * @param {Object} newState
968 * @return {Object} newState
970 History.storeState = function(newState){
972 History.urlToId[newState.url] = newState.id;
975 History.storedStates.push(History.cloneObject(newState));
982 * History.isLastSavedState(newState)
983 * Tests to see if the state is the last state
984 * @param {Object} newState
985 * @return {boolean} isLast
987 History.isLastSavedState = function(newState){
990 newId, oldState, oldId;
993 if ( History.savedStates.length ) {
995 oldState = History.getLastSavedState();
999 isLast = (newId === oldId);
1009 * @param {Object} newState
1010 * @return {boolean} changed
1012 History.saveState = function(newState){
1014 if ( History.isLastSavedState(newState) ) {
1019 History.savedStates.push(History.cloneObject(newState));
1026 * History.getStateByIndex()
1027 * Gets a state by the index
1028 * @param {integer} index
1031 History.getStateByIndex = function(index){
1036 if ( typeof index === 'undefined' ) {
1037 // Get the last inserted
1038 State = History.savedStates[History.savedStates.length-1];
1040 else if ( index < 0 ) {
1042 State = History.savedStates[History.savedStates.length+index];
1045 // Get from the beginning
1046 State = History.savedStates[index];
1054 * History.getCurrentIndex()
1055 * Gets the current index
1058 History.getCurrentIndex = function(){
1063 if(History.savedStates.length < 1) {
1067 index = History.savedStates.length-1;
1072 // ====================================================================
1077 * @param {Location=} location
1078 * Gets the current document hash
1079 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1082 History.getHash = function(doc){
1083 var url = History.getLocationHref(doc),
1085 hash = History.getHashByUrl(url);
1090 * History.unescapeHash()
1091 * normalize and Unescape a Hash
1092 * @param {String} hash
1095 History.unescapeHash = function(hash){
1097 var result = History.normalizeHash(hash);
1100 result = decodeURIComponent(result);
1107 * History.normalizeHash()
1108 * normalize a hash across browsers
1111 History.normalizeHash = function(hash){
1113 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1120 * History.setHash(hash)
1121 * Sets the document hash
1122 * @param {string} hash
1125 History.setHash = function(hash,queue){
1130 if ( queue !== false && History.busy() ) {
1131 // Wait + Push to Queue
1132 //History.debug('History.setHash: we must wait', arguments);
1135 callback: History.setHash,
1143 //History.debug('History.setHash: called',hash);
1145 // Make Busy + Continue
1148 // Check if hash is a state
1149 State = History.extractState(hash,true);
1150 if ( State && !History.emulated.pushState ) {
1151 // Hash is a state so skip the setHash
1152 //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1155 History.pushState(State.data,State.title,State.url,false);
1157 else if ( History.getHash() !== hash ) {
1158 // Hash is a proper hash, so apply it
1160 // Handle browser bugs
1161 if ( History.bugs.setHash ) {
1162 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1164 // Fetch the base page
1165 pageUrl = History.getPageUrl();
1167 // Safari hash apply
1168 History.pushState(null,null,pageUrl+'#'+hash,false);
1171 // Normal hash apply
1172 window.document.location.hash = hash;
1182 * normalize and Escape a Hash
1185 History.escapeHash = function(hash){
1187 var result = History.normalizeHash(hash);
1190 result = window.encodeURIComponent(result);
1193 if ( !History.bugs.hashEscape ) {
1194 // Restore common parts
1196 .replace(/\%21/g,'!')
1197 .replace(/\%26/g,'&')
1198 .replace(/\%3D/g,'=')
1199 .replace(/\%3F/g,'?');
1207 * History.getHashByUrl(url)
1208 * Extracts the Hash from a URL
1209 * @param {string} url
1210 * @return {string} url
1212 History.getHashByUrl = function(url){
1214 var hash = String(url)
1215 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1219 hash = History.unescapeHash(hash);
1226 * History.setTitle(title)
1227 * Applies the title to the document
1228 * @param {State} newState
1231 History.setTitle = function(newState){
1233 var title = newState.title,
1238 firstState = History.getStateByIndex(0);
1239 if ( firstState && firstState.url === newState.url ) {
1240 title = firstState.title||History.options.initialTitle;
1246 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1248 catch ( Exception ) { }
1249 window.document.title = title;
1256 // ====================================================================
1261 * The list of queues to use
1262 * First In, First Out
1264 History.queues = [];
1267 * History.busy(value)
1268 * @param {boolean} value [optional]
1269 * @return {boolean} busy
1271 History.busy = function(value){
1273 if ( typeof value !== 'undefined' ) {
1274 //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
1275 History.busy.flag = value;
1278 else if ( typeof History.busy.flag === 'undefined' ) {
1279 History.busy.flag = false;
1283 if ( !History.busy.flag ) {
1284 // Execute the next item in the queue
1285 window.clearTimeout(History.busy.timeout);
1286 var fireNext = function(){
1288 if ( History.busy.flag ) return;
1289 for ( i=History.queues.length-1; i >= 0; --i ) {
1290 queue = History.queues[i];
1291 if ( queue.length === 0 ) continue;
1292 item = queue.shift();
1293 History.fireQueueItem(item);
1294 History.busy.timeout = window.setTimeout(fireNext,History.options.busyDelay);
1297 History.busy.timeout = window.setTimeout(fireNext,History.options.busyDelay);
1301 return History.busy.flag;
1307 History.busy.flag = false;
1310 * History.fireQueueItem(item)
1312 * @param {Object} item
1313 * @return {Mixed} result
1315 History.fireQueueItem = function(item){
1316 return item.callback.apply(item.scope||History,item.args||[]);
1320 * History.pushQueue(callback,args)
1321 * Add an item to the queue
1322 * @param {Object} item [scope,callback,args,queue]
1324 History.pushQueue = function(item){
1325 // Prepare the queue
1326 History.queues[item.queue||0] = History.queues[item.queue||0]||[];
1329 History.queues[item.queue||0].push(item);
1336 * History.queue (item,queue), (func,queue), (func), (item)
1337 * Either firs the item now if not busy, or adds it to the queue
1339 History.queue = function(item,queue){
1341 if ( typeof item === 'function' ) {
1346 if ( typeof queue !== 'undefined' ) {
1351 if ( History.busy() ) {
1352 History.pushQueue(item);
1354 History.fireQueueItem(item);
1362 * History.clearQueue()
1365 History.clearQueue = function(){
1366 History.busy.flag = false;
1367 History.queues = [];
1372 // ====================================================================
1376 * History.stateChanged
1377 * States whether or not the state has changed since the last double check was initialised
1379 History.stateChanged = false;
1382 * History.doubleChecker
1383 * Contains the timeout used for the double checks
1385 History.doubleChecker = false;
1388 * History.doubleCheckComplete()
1389 * Complete a double check
1392 History.doubleCheckComplete = function(){
1394 History.stateChanged = true;
1397 History.doubleCheckClear();
1404 * History.doubleCheckClear()
1405 * Clear a double check
1408 History.doubleCheckClear = function(){
1410 if ( History.doubleChecker ) {
1411 window.clearTimeout(History.doubleChecker);
1412 History.doubleChecker = false;
1420 * History.doubleCheck()
1421 * Create a double check
1424 History.doubleCheck = function(tryAgain){
1426 History.stateChanged = false;
1427 History.doubleCheckClear();
1429 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1430 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1431 if ( History.bugs.ieDoubleCheck ) {
1433 History.doubleChecker = window.setTimeout(
1435 History.doubleCheckClear();
1436 if ( !History.stateChanged ) {
1437 //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1443 History.options.doubleCheckInterval
1452 // ====================================================================
1456 * History.safariStatePoll()
1457 * Poll the current state
1460 History.safariStatePoll = function(){
1463 // Get the Last State which has the new URL
1465 urlState = History.extractState(History.getLocationHref()),
1468 // Check for a difference
1469 if ( !History.isLastSavedState(urlState) ) {
1470 newState = urlState;
1476 // Check if we have a state with that url
1479 //History.debug('History.safariStatePoll: new');
1480 newState = History.createStateObject();
1483 // Apply the New State
1484 //History.debug('History.safariStatePoll: trigger');
1485 History.Adapter.trigger(window,'popstate');
1492 // ====================================================================
1496 * History.back(queue)
1497 * Send the browser history back one item
1498 * @param {Integer} queue [optional]
1500 History.back = function(queue){
1501 //History.debug('History.back: called', arguments);
1504 if ( queue !== false && History.busy() ) {
1505 // Wait + Push to Queue
1506 //History.debug('History.back: we must wait', arguments);
1509 callback: History.back,
1516 // Make Busy + Continue
1519 // Fix certain browser bugs that prevent the state from changing
1520 History.doubleCheck(function(){
1521 History.back(false);
1532 * History.forward(queue)
1533 * Send the browser history forward one item
1534 * @param {Integer} queue [optional]
1536 History.forward = function(queue){
1537 //History.debug('History.forward: called', arguments);
1540 if ( queue !== false && History.busy() ) {
1541 // Wait + Push to Queue
1542 //History.debug('History.forward: we must wait', arguments);
1545 callback: History.forward,
1552 // Make Busy + Continue
1555 // Fix certain browser bugs that prevent the state from changing
1556 History.doubleCheck(function(){
1557 History.forward(false);
1563 // End forward closure
1568 * History.go(index,queue)
1569 * Send the browser history back or forward index times
1570 * @param {Integer} queue [optional]
1572 History.go = function(index,queue){
1573 //History.debug('History.go: called', arguments);
1581 for ( i=1; i<=index; ++i ) {
1582 History.forward(queue);
1585 else if ( index < 0 ) {
1587 for ( i=-1; i>=index; --i ) {
1588 History.back(queue);
1592 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1600 // ====================================================================
1601 // HTML5 State Support
1603 // Non-Native pushState Implementation
1604 if ( History.emulated.pushState ) {
1606 * Provide Skeleton for HTML4 Browsers
1610 var emptyFunction = function(){};
1611 History.pushState = History.pushState||emptyFunction;
1612 History.replaceState = History.replaceState||emptyFunction;
1613 } // History.emulated.pushState
1615 // Native pushState Implementation
1618 * Use native HTML5 History API Implementation
1622 * History.onPopState(event,extra)
1623 * Refresh the Current State
1625 History.onPopState = function(event,extra){
1627 var stateId = false, newState = false, currentHash, currentState;
1629 // Reset the double check
1630 History.doubleCheckComplete();
1632 // Check for a Hash, and handle apporiatly
1633 currentHash = History.getHash();
1634 if ( currentHash ) {
1636 currentState = History.extractState(currentHash||History.getLocationHref(),true);
1637 if ( currentState ) {
1638 // We were able to parse it, it must be a State!
1639 // Let's forward to replaceState
1640 //History.debug('History.onPopState: state anchor', currentHash, currentState);
1641 History.replaceState(currentState.data, currentState.title, currentState.url, false);
1644 // Traditional Anchor
1645 //History.debug('History.onPopState: traditional anchor', currentHash);
1646 History.Adapter.trigger(window,'anchorchange');
1647 History.busy(false);
1650 // We don't care for hashes
1651 History.expectedStateId = false;
1656 stateId = History.Adapter.extractEventData('state',event,extra) || false;
1660 // Vanilla: Back/forward button was used
1661 newState = History.getStateById(stateId);
1663 else if ( History.expectedStateId ) {
1664 // Vanilla: A new state was pushed, and popstate was called manually
1665 newState = History.getStateById(History.expectedStateId);
1669 newState = History.extractState(History.getLocationHref());
1672 // The State did not exist in our store
1674 // Regenerate the State
1675 newState = History.createStateObject(null,null,History.getLocationHref());
1679 History.expectedStateId = false;
1681 // Check if we are the same state
1682 if ( History.isLastSavedState(newState) ) {
1683 // There has been no change (just the page's hash has finally propagated)
1684 //History.debug('History.onPopState: no change', newState, History.savedStates);
1685 History.busy(false);
1690 History.storeState(newState);
1691 History.saveState(newState);
1693 // Force update of the title
1694 History.setTitle(newState);
1697 History.Adapter.trigger(window,'statechange');
1698 History.busy(false);
1703 History.Adapter.bind(window,'popstate',History.onPopState);
1706 * History.pushState(data,title,url)
1707 * Add a new State to the history object, become it, and trigger onpopstate
1708 * We have to trigger for HTML4 compatibility
1709 * @param {object} data
1710 * @param {string} title
1711 * @param {string} url
1714 History.pushState = function(data,title,url,queue){
1715 //History.debug('History.pushState: called', arguments);
1718 if ( History.getHashByUrl(url) && History.emulated.pushState ) {
1719 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1723 if ( queue !== false && History.busy() ) {
1724 // Wait + Push to Queue
1725 //History.debug('History.pushState: we must wait', arguments);
1728 callback: History.pushState,
1735 // Make Busy + Continue
1738 // Create the newState
1739 var newState = History.createStateObject(data,title,url);
1742 if ( History.isLastSavedState(newState) ) {
1743 // Won't be a change
1744 History.busy(false);
1747 // Store the newState
1748 History.storeState(newState);
1749 History.expectedStateId = newState.id;
1751 // Push the newState
1752 history.pushState(newState.id,newState.title,newState.url);
1755 History.Adapter.trigger(window,'popstate');
1758 // End pushState closure
1763 * History.replaceState(data,title,url)
1764 * Replace the State and trigger onpopstate
1765 * We have to trigger for HTML4 compatibility
1766 * @param {object} data
1767 * @param {string} title
1768 * @param {string} url
1771 History.replaceState = function(data,title,url,queue){
1772 //History.debug('History.replaceState: called', arguments);
1775 if ( History.getHashByUrl(url) && History.emulated.pushState ) {
1776 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1780 if ( queue !== false && History.busy() ) {
1781 // Wait + Push to Queue
1782 //History.debug('History.replaceState: we must wait', arguments);
1785 callback: History.replaceState,
1792 // Make Busy + Continue
1795 // Create the newState
1796 var newState = History.createStateObject(data,title,url);
1799 if ( History.isLastSavedState(newState) ) {
1800 // Won't be a change
1801 History.busy(false);
1804 // Store the newState
1805 History.storeState(newState);
1806 History.expectedStateId = newState.id;
1808 // Push the newState
1809 history.replaceState(newState.id,newState.title,newState.url);
1812 History.Adapter.trigger(window,'popstate');
1815 // End replaceState closure
1819 } // !History.emulated.pushState
1822 // ====================================================================
1828 if ( sessionStorage ) {
1831 History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
1838 History.normalizeStore();
1843 History.normalizeStore();
1847 * Clear Intervals on exit to prevent memory leaks
1849 History.Adapter.bind(window,"unload",History.clearAllIntervals);
1852 * Create the initial State
1854 History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
1857 * Bind for Saving Store
1859 if ( sessionStorage ) {
1860 // When the page is closed
1861 History.onUnload = function(){
1863 var currentStore, item, currentStoreString;
1867 currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
1874 currentStore.idToState = currentStore.idToState || {};
1875 currentStore.urlToId = currentStore.urlToId || {};
1876 currentStore.stateToId = currentStore.stateToId || {};
1879 for ( item in History.idToState ) {
1880 if ( !History.idToState.hasOwnProperty(item) ) {
1883 currentStore.idToState[item] = History.idToState[item];
1885 for ( item in History.urlToId ) {
1886 if ( !History.urlToId.hasOwnProperty(item) ) {
1889 currentStore.urlToId[item] = History.urlToId[item];
1891 for ( item in History.stateToId ) {
1892 if ( !History.stateToId.hasOwnProperty(item) ) {
1895 currentStore.stateToId[item] = History.stateToId[item];
1899 History.store = currentStore;
1900 History.normalizeStore();
1902 // In Safari, going into Private Browsing mode causes the
1903 // Session Storage object to still exist but if you try and use
1904 // or set any property/function of it it throws the exception
1905 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
1906 // add something to storage that exceeded the quota." infinitely
1908 currentStoreString = JSON.stringify(currentStore);
1911 sessionStorage.setItem('History.store', currentStoreString);
1914 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
1915 if (sessionStorage.length) {
1916 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
1917 // removing/resetting the storage can work.
1918 sessionStorage.removeItem('History.store');
1919 sessionStorage.setItem('History.store', currentStoreString);
1921 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
1929 // For Internet Explorer
1930 History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
1932 // For Other Browsers
1933 History.Adapter.bind(window,'beforeunload',History.onUnload);
1934 History.Adapter.bind(window,'unload',History.onUnload);
1936 // Both are enabled for consistency
1939 // Non-Native pushState Implementation
1940 if ( !History.emulated.pushState ) {
1941 // Be aware, the following is only for native pushState implementations
1942 // If you are wanting to include something for all browsers
1943 // Then include it above this if block
1948 if ( History.bugs.safariPoll ) {
1949 History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
1953 * Ensure Cross Browser Compatibility
1955 if ( window.navigator.vendor === 'Apple Computer, Inc.' || (window.navigator.appCodeName||'') === 'Mozilla' ) {
1957 * Fix Safari HashChange Issue
1961 History.Adapter.bind(window,'hashchange',function(){
1962 History.Adapter.trigger(window,'popstate');
1966 if ( History.getHash() ) {
1967 History.Adapter.onDomLoad(function(){
1968 History.Adapter.trigger(window,'hashchange');
1973 } // !History.emulated.pushState
1976 }; // History.initCore
1978 // Try to Initialise History
1979 if (!History.options || !History.options.delayInit) {