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,
31 * How long should the interval be before we perform a double check
33 doubleCheckInterval : 500,
37 * Force this.not to append suid
43 * How long should we wait between store calls
49 * How long should we wait between busy events
55 * If true will enable debug messages to be logged
61 * What is the title of the initial state
67 * If true, will force HTMl4 mode (hashtags)
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 * Is History enabled?
120 // ====================================================================
125 * The store for all session specific data
131 * 1-1: State ID to State Object
137 * 1-1: State String to State ID
143 * 1-1: State URL to State ID
149 * Store the states in an array
151 storedStates : false,
155 * Saved the states in an array
161 * The list of queues to use
162 * First In, First Out
171 // ====================================================================
175 * History.stateChanged
176 * States whether or not the state has changed since the last double check was initialised
178 stateChanged : false,
181 * History.doubleChecker
182 * Contains the timeout used for the double checks
184 doubleChecker : false,
187 // Initialise History
188 init : function(options)
191 var emptyFunction = function(){};
195 this.initialTitle = window.document.title;
200 this.storedStates=[];
204 Roo.apply(this,options)
206 // Check Load Status of Adapter
207 //if ( typeof this.Adapter === 'undefined' ) {
211 // Check Load Status of Core
212 if ( typeof this.initCore !== 'undefined' ) {
216 // Check Load Status of HTML4 Support
217 if ( typeof this.initHtml4 !== 'undefined' ) {
223 this.enabled = !this.emulated.pushState;
225 if ( this.emulated.pushState ) {
229 this.pushState = emptyFunction;
230 this.replaceState = emptyFunction;
233 this.Adapter.bind(window,'popstate',this.onPopState);
239 if ( this.sessionStorage ) {
242 this.store = JSON.parse(this.sessionStorage.getItem('Roo.History.store'))||{};
249 this.onUnload = emptyFunction;
253 this.normalizeStore();
255 * Clear Intervals on exit to prevent memory leaks
257 this.Adapter.bind(window,"unload",this.clearAllIntervals);
260 * Create the initial State
262 this.saveState(this.storeState(this.extractState(this.getLocationHref(),true)));
271 // ========================================================================
275 initCore : function(options){
277 this.intervalList = [];
281 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
282 this.sessionStorage.setItem('TEST', '1');
283 this.sessionStorage.removeItem('TEST');
285 this.sessionStorage = false;
289 if ( typeof this.initCore.initialized !== 'undefined' ) {
294 this.initCore.initialized = true;
303 * Clears all setInterval instances.
305 clearAllIntervals: function()
307 var i, il = this.intervalList;
308 if (typeof il !== "undefined" && il !== null) {
309 for (i = 0; i < il.length; i++) {
310 clearInterval(il[i]);
312 this.intervalList = null;
317 // ====================================================================
321 * debugLog(message,...)
322 * Logs the passed arguments if debug enabled
324 debugLog : function()
326 if ( (this.debug||false) ) {
327 Roo.log.apply(this,arguments);
333 // ====================================================================
337 * getInternetExplorerMajorVersion()
338 * Get's the major version of Internet Explorer
340 * @license Public Domain
341 * @author Benjamin Arthur Lupton <contact@balupton.com>
342 * @author James Padolsey <https://gist.github.com/527683>
344 getInternetExplorerMajorVersion : function(){
345 var result = this.getInternetExplorerMajorVersion.cached =
346 (typeof this.getInternetExplorerMajorVersion.cached !== 'undefined')
347 ? this.getInternetExplorerMajorVersion.cached
350 div = window.document.createElement('div'),
351 all = div.getElementsByTagName('i');
352 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
353 return (v > 4) ? v : false;
360 * isInternetExplorer()
361 * Are we using Internet Explorer?
363 * @license Public Domain
364 * @author Benjamin Arthur Lupton <contact@balupton.com>
366 isInternetExplorer : function(){
368 this.isInternetExplorer.cached =
369 (typeof this.isInternetExplorer.cached !== 'undefined')
370 ? this.isInternetExplorer.cached
371 : Boolean(this.getInternetExplorerMajorVersion())
377 * Which features require emulating?
385 initEmulated : function()
389 if (this.html4Mode) {
395 this.emulated.pushState = !Boolean(
396 window.history && window.history.pushState && window.history.replaceState
398 (/ 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) */
399 || (/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 */
402 this.emulated.hashChange = Boolean(
403 !(('onhashchange' in window) || ('onhashchange' in window.document))
405 (this.isInternetExplorer() && this.getInternetExplorerMajorVersion() < 8)
414 * Checks to see if the Object is Empty
415 * @param {Object} obj
418 isEmptyObject = function(obj) {
419 for ( var name in obj ) {
420 if ( obj.hasOwnProperty(name) ) {
429 * Clones a object and eliminate all references to the original contexts
430 * @param {Object} obj
433 cloneObject = function(obj) {
436 hash = JSON.stringify(obj);
437 newObj = JSON.parse(hash);
446 // ====================================================================
451 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
452 * @return {String} rootUrl
454 getRootUrl = function(){
456 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
457 if ( window.document.location.port||false ) {
458 rootUrl += ':'+window.document.location.port;
468 * Fetches the `href` attribute of the `<base href="...">` element if it exists
469 * @return {String} baseHref
471 getBaseHref = function(){
474 baseElements = window.document.getElementsByTagName('base'),
478 // Test for Base Element
479 if ( baseElements.length === 1 ) {
480 // Prepare for Base Element
481 baseElement = baseElements[0];
482 baseHref = baseElement.href.replace(/[^\/]+$/,'');
485 // Adjust trailing slash
486 baseHref = baseHref.replace(/\/+$/,'');
487 if ( baseHref ) baseHref += '/';
495 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
496 * @return {String} baseUrl
498 getBaseUrl = function(){
500 var baseUrl = this.getBaseHref()||this.getBasePageUrl()||this.getRootUrl();
508 * Fetches the URL of the current page
509 * @return {String} pageUrl
511 getPageUrl = function(){
514 State = this.getState(false,false),
515 stateUrl = (State||{}).url||this.getLocationHref(),
519 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
520 return (/\./).test(part) ? part : part+'/';
529 * Fetches the Url of the directory of the current page
530 * @return {String} basePageUrl
532 getBasePageUrl = function(){
534 var basePageUrl = (this.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
535 return (/[^\/]$/).test(part) ? '' : part;
536 }).replace(/\/+$/,'')+'/';
544 * Ensures that we have an absolute URL and not a relative URL
545 * @param {string} url
546 * @param {Boolean} allowBaseHref
547 * @return {string} fullUrl
549 getFullUrl = function(url,allowBaseHref){
551 var fullUrl = url, firstChar = url.substring(0,1);
552 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
555 if ( /[a-z]+\:\/\//.test(url) ) {
558 else if ( firstChar === '/' ) {
560 fullUrl = this.getRootUrl()+url.replace(/^\/+/,'');
562 else if ( firstChar === '#' ) {
564 fullUrl = this.getPageUrl().replace(/#.*/,'')+url;
566 else if ( firstChar === '?' ) {
568 fullUrl = this.getPageUrl().replace(/[\?#].*/,'')+url;
572 if ( allowBaseHref ) {
573 fullUrl = this.getBaseUrl()+url.replace(/^(\.\/)+/,'');
575 fullUrl = this.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
577 // We have an if condition above as we do not want hashes
578 // which are relative to the baseHref in our URLs
579 // as if the baseHref changes, then all our bookmarks
580 // would now point to different locations
581 // whereas the basePageUrl will always stay the same
585 return fullUrl.replace(/\#$/,'');
590 * Ensures that we have a relative URL and not a absolute URL
591 * @param {string} url
592 * @return {string} url
594 getShortUrl = function(url){
596 var shortUrl = url, baseUrl = this.getBaseUrl(), rootUrl = this.getRootUrl();
599 if ( this.emulated.pushState ) {
600 // We are in a if statement as when pushState is not emulated
601 // The actual url these short urls are relative to can change
602 // So within the same session, we the url may end up somewhere different
603 shortUrl = shortUrl.replace(baseUrl,'');
607 shortUrl = shortUrl.replace(rootUrl,'/');
609 // Ensure we can still detect it as a state
610 if ( this.isTraditionalAnchor(shortUrl) ) {
611 shortUrl = './'+shortUrl;
615 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
622 * getLocationHref(document)
623 * Returns a normalized version of document.location.href
624 * accounting for browser inconsistencies, etc.
626 * This URL will be URI-encoded and will include the hash
628 * @param {object} document
629 * @return {string} url
631 getLocationHref = function(doc) {
632 doc = doc || window.document;
634 // most of the time, this will be true
635 if (doc.URL === doc.location.href)
636 return doc.location.href;
638 // some versions of webkit URI-decode document.location.href
639 // but they leave document.URL in an encoded state
640 if (doc.location.href === decodeURIComponent(doc.URL))
643 // FF 3.6 only updates document.URL when a page is reloaded
644 // document.location.href is updated correctly
645 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
646 return doc.location.href;
648 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
649 return doc.location.href;
651 return doc.URL || doc.location.href;
658 * Noramlize the store by adding necessary values
660 normalizeStore = function(){
661 this.store.idToState = this.store.idToState||{};
662 this.store.urlToId = this.store.urlToId||{};
663 this.store.stateToId = this.store.stateToId||{};
668 * Get an object containing the data, title and url of the current state
669 * @param {Boolean} friendly
670 * @param {Boolean} create
671 * @return {Object} State
673 getState : function(friendly,create){
675 if ( typeof friendly === 'undefined' ) { friendly = true; }
676 if ( typeof create === 'undefined' ) { create = true; }
679 var State = this.getLastSavedState();
682 if ( !State && create ) {
683 State = this.createStateObject();
688 State = this.cloneObject(State);
689 State.url = this.cleanUrl||State.url;
697 * getIdByState(State)
698 * Gets a ID for a State
699 * @param {State} newState
700 * @return {String} id
702 getIdByState = function(newState){
705 var id = this.extractId(newState.url),
709 // Find ID via State String
710 str = this.getStateString(newState);
711 if ( typeof this.stateToId[str] !== 'undefined' ) {
712 id = this.stateToId[str];
714 else if ( typeof this.store.stateToId[str] !== 'undefined' ) {
715 id = this.store.stateToId[str];
720 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
721 if ( typeof this.idToState[id] === 'undefined' && typeof this.store.idToState[id] === 'undefined' ) {
726 // Apply the new State to the ID
727 this.stateToId[str] = id;
728 this.idToState[id] = newState;
737 * normalizeState(State)
738 * Expands a State Object
739 * @param {object} State
742 normalizeState = function(oldState){
744 var newState, dataNotEmpty;
747 if ( !oldState || (typeof oldState !== 'object') ) {
752 if ( typeof oldState.normalized !== 'undefined' ) {
757 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
761 // ----------------------------------------------------------------
765 newState.normalized = true;
766 newState.title = oldState.title||'';
767 newState.url = this.getFullUrl(oldState.url?oldState.url:(this.getLocationHref()));
768 newState.hash = this.getShortUrl(newState.url);
769 newState.data = this.cloneObject(oldState.data);
772 newState.id = this.getIdByState(newState);
774 // ----------------------------------------------------------------
777 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
778 newState.url = newState.cleanUrl;
780 // Check to see if we have more than just a url
781 dataNotEmpty = !this.isEmptyObject(newState.data);
784 if ( (newState.title || dataNotEmpty) && this.disableSuid !== true ) {
786 newState.hash = this.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
787 if ( !/\?/.test(newState.hash) ) {
788 newState.hash += '?';
790 newState.hash += '&_suid='+newState.id;
793 // Create the Hashed URL
794 newState.hashedUrl = this.getFullUrl(newState.hash);
796 // ----------------------------------------------------------------
798 // Update the URL if we have a duplicate
799 if ( (this.emulated.pushState || this.bugs.safariPoll) && this.hasUrlDuplicate(newState) ) {
800 newState.url = newState.hashedUrl;
803 // ----------------------------------------------------------------
810 * createStateObject(data,title,url)
811 * Creates a object based on the data, title and url state params
812 * @param {object} data
813 * @param {string} title
814 * @param {string} url
817 createStateObject = function(data,title,url){
826 State = this.normalizeState(State);
834 * Get a state by it's UID
837 getStateById = function(id){
842 var State = this.idToState[id] || this.store.idToState[id] || undefined;
849 * Get a State's String
850 * @param {State} passedState
852 getStateString = function(passedState){
854 var State, cleanedState, str;
857 State = this.normalizeState(passedState);
862 title: passedState.title,
867 str = JSON.stringify(cleanedState);
875 * @param {State} passedState
876 * @return {String} id
878 getStateId = function(passedState){
883 State = this.normalizeState(passedState);
893 * getHashByState(State)
894 * Creates a Hash for the State Object
895 * @param {State} passedState
896 * @return {String} hash
898 getHashByState = function(passedState){
903 State = this.normalizeState(passedState);
913 * extractId(url_or_hash)
914 * Get a State ID by it's URL or Hash
915 * @param {string} url_or_hash
916 * @return {string} id
918 this.extractId = function ( url_or_hash ) {
920 var id,parts,url, tmp;
924 // If the URL has a #, use the id from before the #
925 if (url_or_hash.indexOf('#') != -1)
927 tmp = url_or_hash.split("#")[0];
934 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
935 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
936 id = parts ? String(parts[2]||'') : '';
943 * isTraditionalAnchor
944 * Checks to see if the url is a traditional anchor or not
945 * @param {String} url_or_hash
948 isTraditionalAnchor = function(url_or_hash){
950 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
953 return isTraditional;
958 * Get a State by it's URL or Hash
959 * @param {String} url_or_hash
960 * @return {State|null}
962 extractState = function(url_or_hash,create){
964 var State = null, id, url;
965 create = create||false;
968 id = this.extractId(url_or_hash);
970 State = this.getStateById(id);
973 // Fetch SUID returned no State
976 url = this.getFullUrl(url_or_hash);
979 id = this.getIdByUrl(url)||false;
981 State = this.getStateById(id);
985 if ( !State && create && !this.isTraditionalAnchor(url_or_hash) ) {
986 State = this.createStateObject(null,null,url);
996 * Get a State ID by a State URL
998 getIdByUrl = function(url){
1000 var id = this.urlToId[url] || this.store.urlToId[url] || undefined;
1007 * getLastSavedState()
1008 * Get an object containing the data, title and url of the current state
1009 * @return {Object} State
1011 getLastSavedState = function(){
1012 return this.savedStates[this.savedStates.length-1]||undefined;
1016 * getLastStoredState()
1017 * Get an object containing the data, title and url of the current state
1018 * @return {Object} State
1020 getLastStoredState = function(){
1021 return this.storedStates[this.storedStates.length-1]||undefined;
1026 * Checks if a Url will have a url conflict
1027 * @param {Object} newState
1028 * @return {Boolean} hasDuplicate
1030 hasUrlDuplicate = function(newState) {
1032 var hasDuplicate = false,
1036 oldState = this.extractState(newState.url);
1039 hasDuplicate = oldState && oldState.id !== newState.id;
1042 return hasDuplicate;
1048 * @param {Object} newState
1049 * @return {Object} newState
1051 storeState = function(newState){
1053 this.urlToId[newState.url] = newState.id;
1056 this.storedStates.push(this.cloneObject(newState));
1063 * isLastSavedState(newState)
1064 * Tests to see if the state is the last state
1065 * @param {Object} newState
1066 * @return {boolean} isLast
1068 isLastSavedState = function(newState){
1071 newId, oldState, oldId;
1074 if ( this.savedStates.length ) {
1075 newId = newState.id;
1076 oldState = this.getLastSavedState();
1077 oldId = oldState.id;
1080 isLast = (newId === oldId);
1090 * @param {Object} newState
1091 * @return {boolean} changed
1093 saveState = function(newState){
1095 if ( this.isLastSavedState(newState) ) {
1100 this.savedStates.push(this.cloneObject(newState));
1108 * Gets a state by the index
1109 * @param {integer} index
1112 getStateByIndex = function(index){
1117 if ( typeof index === 'undefined' ) {
1118 // Get the last inserted
1119 State = this.savedStates[this.savedStates.length-1];
1121 else if ( index < 0 ) {
1123 State = this.savedStates[this.savedStates.length+index];
1126 // Get from the beginning
1127 State = this.savedStates[index];
1136 * Gets the current index
1139 getCurrentIndex = function(){
1144 if(this.savedStates.length < 1) {
1148 index = this.savedStates.length-1;
1153 // ====================================================================
1158 * @param {Location=} location
1159 * Gets the current document hash
1160 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1163 getHash = function(doc){
1164 var url = this.getLocationHref(doc),
1166 hash = this.getHashByUrl(url);
1172 * normalize and Unescape a Hash
1173 * @param {String} hash
1176 unescapeHash = function(hash){
1178 var result = this.normalizeHash(hash);
1181 result = decodeURIComponent(result);
1189 * normalize a hash across browsers
1192 normalizeHash = function(hash){
1194 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1202 * Sets the document hash
1203 * @param {string} hash
1204 * @return {Roo.History}
1206 setHash = function(hash,queue){
1211 if ( queue !== false && this.busy() ) {
1212 // Wait + Push to Queue
1213 //this.debug('this.setHash: we must wait', arguments);
1216 callback: this.setHash,
1224 //this.debug('this.setHash: called',hash);
1226 // Make Busy + Continue
1229 // Check if hash is a state
1230 State = this.extractState(hash,true);
1231 if ( State && !this.emulated.pushState ) {
1232 // Hash is a state so skip the setHash
1233 //this.debug('this.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1236 this.pushState(State.data,State.title,State.url,false);
1238 else if ( this.getHash() !== hash ) {
1239 // Hash is a proper hash, so apply it
1241 // Handle browser bugs
1242 if ( this.bugs.setHash ) {
1243 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1245 // Fetch the base page
1246 pageUrl = this.getPageUrl();
1248 // Safari hash apply
1249 this.pushState(null,null,pageUrl+'#'+hash,false);
1252 // Normal hash apply
1253 window.document.location.hash = hash;
1263 * normalize and Escape a Hash
1266 escapeHash = function(hash){
1268 var result = normalizeHash(hash);
1271 result = window.encodeURIComponent(result);
1274 if ( !this.bugs.hashEscape ) {
1275 // Restore common parts
1277 .replace(/\%21/g,'!')
1278 .replace(/\%26/g,'&')
1279 .replace(/\%3D/g,'=')
1280 .replace(/\%3F/g,'?');
1289 * Extracts the Hash from a URL
1290 * @param {string} url
1291 * @return {string} url
1293 getHashByUrl = function(url){
1295 var hash = String(url)
1296 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1300 hash = this.unescapeHash(hash);
1308 * Applies the title to the document
1309 * @param {State} newState
1312 setTitle = function(newState){
1314 var title = newState.title,
1319 firstState = this.getStateByIndex(0);
1320 if ( firstState && firstState.url === newState.url ) {
1321 title = firstState.title||this.initialTitle;
1327 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1329 catch ( Exception ) { }
1330 window.document.title = title;
1337 // ====================================================================
1343 * @param {boolean} value [optional]
1344 * @return {boolean} busy
1346 busy = function(value){
1348 if ( typeof value !== 'undefined' ) {
1349 //this.debug('this.busy: changing ['+(this.busy.flag||false)+'] to ['+(value||false)+']', this.queues.length);
1350 this.busy_flag = value;
1353 else if ( typeof this.busy_flag === 'undefined' ) {
1354 this.busy_flag = false;
1358 if ( !this.busy_flag ) {
1359 // Execute the next item in the queue
1360 window.clearTimeout(this.busy.timeout);
1361 var fireNext = function(){
1363 if ( this.busy_flag ) return;
1364 for ( i=this.queues.length-1; i >= 0; --i ) {
1365 queue = this.queues[i];
1366 if ( queue.length === 0 ) continue;
1367 item = queue.shift();
1368 this.fireQueueItem(item);
1369 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1372 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1376 return this.busy_flag;
1382 * fireQueueItem(item)
1384 * @param {Object} item
1385 * @return {Mixed} result
1387 fireQueueItem = function(item){
1388 return item.callback.apply(item.scope||this,item.args||[]);
1392 * pushQueue(callback,args)
1393 * Add an item to the queue
1394 * @param {Object} item [scope,callback,args,queue]
1396 pushQueue = function(item){
1397 // Prepare the queue
1398 this.queues[item.queue||0] = this.queues[item.queue||0]||[];
1401 this.queues[item.queue||0].push(item);
1408 * queue (item,queue), (func,queue), (func), (item)
1409 * Either firs the item now if not busy, or adds it to the queue
1411 queue = function(item,queue){
1413 if ( typeof item === 'function' ) {
1418 if ( typeof queue !== 'undefined' ) {
1423 if ( this.busy() ) {
1424 this.pushQueue(item);
1426 this.fireQueueItem(item);
1437 clearQueue = function(){
1438 this.busy_flag = false;
1446 * doubleCheckComplete()
1447 * Complete a double check
1448 * @return {Roo.History}
1450 doubleCheckComplete = function(){
1452 this.stateChanged = true;
1455 this.doubleCheckClear();
1462 * doubleCheckClear()
1463 * Clear a double check
1464 * @return {Roo.History}
1466 doubleCheckClear = function(){
1468 if ( this.doubleChecker ) {
1469 window.clearTimeout(this.doubleChecker);
1470 this.doubleChecker = false;
1479 * Create a double check
1480 * @return {Roo.History}
1482 doubleCheck = function(tryAgain){
1484 this.stateChanged = false;
1485 this.doubleCheckClear();
1487 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1488 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1489 if ( this.bugs.ieDoubleCheck ) {
1491 this.doubleChecker = window.setTimeout(
1493 this.doubleCheckClear();
1494 if ( !this.stateChanged ) {
1495 //this.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1501 this.doubleCheckInterval
1510 // ====================================================================
1515 * Poll the current state
1516 * @return {Roo.History}
1518 safariStatePoll = function(){
1521 // Get the Last State which has the new URL
1523 urlState = this.extractState(this.getLocationHref()),
1526 // Check for a difference
1527 if ( !this.isLastSavedState(urlState) ) {
1528 newState = urlState;
1534 // Check if we have a state with that url
1537 //this.debug('this.safariStatePoll: new');
1538 newState = this.createStateObject();
1541 // Apply the New State
1542 //this.debug('this.safariStatePoll: trigger');
1543 this.Adapter.trigger(window,'popstate');
1550 // ====================================================================
1555 * Send the browser history back one item
1556 * @param {Integer} queue [optional]
1558 back = function(queue){
1559 //this.debug('this.back: called', arguments);
1562 if ( queue !== false && this.busy() ) {
1563 // Wait + Push to Queue
1564 //this.debug('this.back: we must wait', arguments);
1567 callback: this.back,
1574 // Make Busy + Continue
1577 // Fix certain browser bugs that prevent the state from changing
1578 this.doubleCheck(function(){
1591 * Send the browser history forward one item
1592 * @param {Integer} queue [optional]
1594 forward = function(queue){
1595 //this.debug('this.forward: called', arguments);
1598 if ( queue !== false && this.busy() ) {
1599 // Wait + Push to Queue
1600 //this.debug('this.forward: we must wait', arguments);
1603 callback: this.forward,
1610 // Make Busy + Continue
1614 // Fix certain browser bugs that prevent the state from changing
1615 this.doubleCheck(function(){
1622 // End forward closure
1628 * Send the browser history back or forward index times
1629 * @param {Integer} queue [optional]
1631 go = function(index,queue){
1632 //this.debug('this.go: called', arguments);
1640 for ( i=1; i<=index; ++i ) {
1641 this.forward(queue);
1644 else if ( index < 0 ) {
1646 for ( i=-1; i>=index; --i ) {
1651 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1659 // ====================================================================
1660 // HTML5 State Support
1664 * Use native HTML5 History API Implementation
1668 * onPopState(event,extra)
1669 * Refresh the Current State
1671 onPopState = function(event,extra){
1673 var stateId = false, newState = false, currentHash, currentState;
1675 // Reset the double check
1676 this.doubleCheckComplete();
1678 // Check for a Hash, and handle apporiatly
1679 currentHash = this.getHash();
1680 if ( currentHash ) {
1682 currentState = this.extractState(currentHash||this.getLocationHref(),true);
1683 if ( currentState ) {
1684 // We were able to parse it, it must be a State!
1685 // Let's forward to replaceState
1686 //this.debug('this.onPopState: state anchor', currentHash, currentState);
1687 this.replaceState(currentState.data, currentState.title, currentState.url, false);
1690 // Traditional Anchor
1691 //this.debug('this.onPopState: traditional anchor', currentHash);
1692 this.Adapter.trigger(window,'anchorchange');
1696 // We don't care for hashes
1697 this.expectedStateId = false;
1702 stateId = this.Adapter.extractEventData('state',event,extra) || false;
1706 // Vanilla: Back/forward button was used
1707 newState = this.getStateById(stateId);
1709 else if ( this.expectedStateId ) {
1710 // Vanilla: A new state was pushed, and popstate was called manually
1711 newState = this.getStateById(this.expectedStateId);
1715 newState = this.extractState(this.getLocationHref());
1718 // The State did not exist in our store
1720 // Regenerate the State
1721 newState = this.createStateObject(null,null,this.getLocationHref());
1725 this.expectedStateId = false;
1727 // Check if we are the same state
1728 if ( this.isLastSavedState(newState) ) {
1729 // There has been no change (just the page's hash has finally propagated)
1730 //this.debug('this.onPopState: no change', newState, this.savedStates);
1736 this.storeState(newState);
1737 this.saveState(newState);
1739 // Force update of the title
1740 this.setTitle(newState);
1743 this.Adapter.trigger(window,'statechange');
1757 * pushState(data,title,url)
1758 * Add a new State to the history object, become it, and trigger onpopstate
1759 * We have to trigger for HTML4 compatibility
1760 * @param {object} data
1761 * @param {string} title
1762 * @param {string} url
1765 pushState = function(data,title,url,queue){
1766 //this.debug('this.pushState: called', arguments);
1769 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1770 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1774 if ( queue !== false && this.busy() ) {
1775 // Wait + Push to Queue
1776 //this.debug('this.pushState: we must wait', arguments);
1779 callback: this.pushState,
1786 // Make Busy + Continue
1789 // Create the newState
1790 var newState = this.createStateObject(data,title,url);
1793 if ( this.isLastSavedState(newState) ) {
1794 // Won't be a change
1798 // Store the newState
1799 this.storeState(newState);
1800 this.expectedStateId = newState.id;
1802 // Push the newState
1803 history.pushState(newState.id,newState.title,newState.url);
1806 this.Adapter.trigger(window,'popstate');
1809 // End pushState closure
1814 * replaceState(data,title,url)
1815 * Replace the State and trigger onpopstate
1816 * We have to trigger for HTML4 compatibility
1817 * @param {object} data
1818 * @param {string} title
1819 * @param {string} url
1822 replaceState = function(data,title,url,queue){
1823 //this.debug('this.replaceState: called', arguments);
1826 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1827 throw new Error('this.js does not support states with fragement-identifiers (hashes/anchors).');
1831 if ( queue !== false && this.busy() ) {
1832 // Wait + Push to Queue
1833 //this.debug('this.replaceState: we must wait', arguments);
1836 callback: this.replaceState,
1843 // Make Busy + Continue
1846 // Create the newState
1847 var newState = this.createStateObject(data,title,url);
1850 if ( this.isLastSavedState(newState) ) {
1851 // Won't be a change
1855 // Store the newState
1856 this.storeState(newState);
1857 this.expectedStateId = newState.id;
1859 // Push the newState
1860 history.replaceState(newState.id,newState.title,newState.url);
1863 this.Adapter.trigger(window,'popstate');
1866 // End replaceState closure
1871 // ====================================================================
1875 * Bind for Saving Store
1877 if ( sessionStorage ) {
1878 // When the page is closed
1879 History.onUnload = function(){
1881 var currentStore, item, currentStoreString;
1885 currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
1892 currentStore.idToState = currentStore.idToState || {};
1893 currentStore.urlToId = currentStore.urlToId || {};
1894 currentStore.stateToId = currentStore.stateToId || {};
1897 for ( item in History.idToState ) {
1898 if ( !History.idToState.hasOwnProperty(item) ) {
1901 currentStore.idToState[item] = History.idToState[item];
1903 for ( item in History.urlToId ) {
1904 if ( !History.urlToId.hasOwnProperty(item) ) {
1907 currentStore.urlToId[item] = History.urlToId[item];
1909 for ( item in History.stateToId ) {
1910 if ( !History.stateToId.hasOwnProperty(item) ) {
1913 currentStore.stateToId[item] = History.stateToId[item];
1917 History.store = currentStore;
1918 History.normalizeStore();
1920 // In Safari, going into Private Browsing mode causes the
1921 // Session Storage object to still exist but if you try and use
1922 // or set any property/function of it it throws the exception
1923 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
1924 // add something to storage that exceeded the quota." infinitely
1926 currentStoreString = JSON.stringify(currentStore);
1929 sessionStorage.setItem('History.store', currentStoreString);
1932 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
1933 if (sessionStorage.length) {
1934 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
1935 // removing/resetting the storage can work.
1936 sessionStorage.removeItem('History.store');
1937 sessionStorage.setItem('History.store', currentStoreString);
1939 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
1947 // For Internet Explorer
1948 History.intervalList.push(setInterval(History.onUnload,this.storeInterval));
1950 // For Other Browsers
1951 History.Adapter.bind(window,'beforeunload',History.onUnload);
1952 History.Adapter.bind(window,'unload',History.onUnload);
1954 // Both are enabled for consistency
1957 // Non-Native pushState Implementation
1958 if ( !History.emulated.pushState ) {
1959 // Be aware, the following is only for native pushState implementations
1960 // If you are wanting to include something for all browsers
1961 // Then include it above this if block
1966 if ( History.bugs.safariPoll ) {
1967 History.intervalList.push(setInterval(History.safariStatePoll, this.safariPollInterval));
1971 * Ensure Cross Browser Compatibility
1973 if ( window.navigator.vendor === 'Apple Computer, Inc.' || (window.navigator.appCodeName||'') === 'Mozilla' ) {
1975 * Fix Safari HashChange Issue
1979 History.Adapter.bind(window,'hashchange',function(){
1980 History.Adapter.trigger(window,'popstate');
1984 if ( History.getHash() ) {
1985 History.Adapter.onDomLoad(function(){
1986 History.Adapter.trigger(window,'hashchange');
1991 } // !History.emulated.pushState
1994 }; // History.initCore
1996 // Try to Initialise History
1997 if (!History.options || !History.options.delayInit) {