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 // ========================================================================
85 sessionStorage : false, // sessionStorage
87 intervalList : false, // array normally.
90 init : function(options){
92 initialTitle : window.document.title,
94 Roo.apply(this,options)
96 // Check Load Status of Adapter
97 //if ( typeof this.Adapter === 'undefined' ) {
101 // Check Load Status of Core
102 if ( typeof this.initCore !== 'undefined' ) {
106 // Check Load Status of HTML4 Support
107 if ( typeof this.initHtml4 !== 'undefined' ) {
116 // ========================================================================
120 initCore : function(options){
122 this.intervalList = [];
126 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
127 this.sessionStorage.setItem('TEST', '1');
128 this.sessionStorage.removeItem('TEST');
130 this.sessionStorage = false;
134 if ( typeof this.initCore.initialized !== 'undefined' ) {
139 this.initCore.initialized = true;
147 * History.clearAllIntervals
148 * Clears all setInterval instances.
150 clearAllIntervals: function(){
151 var i, il = this.intervalList;
152 if (typeof il !== "undefined" && il !== null) {
153 for (i = 0; i < il.length; i++) {
154 clearInterval(il[i]);
156 this.intervalList = null;
161 // ====================================================================
165 * History.debugLog(message,...)
166 * Logs the passed arguments if debug enabled
168 debugLog : function(){
169 if ( (this.debug||false) ) {
170 Roo.log.apply(History,arguments);
176 // ====================================================================
180 * History.getInternetExplorerMajorVersion()
181 * Get's the major version of Internet Explorer
183 * @license Public Domain
184 * @author Benjamin Arthur Lupton <contact@balupton.com>
185 * @author James Padolsey <https://gist.github.com/527683>
187 History.getInternetExplorerMajorVersion = function(){
188 var result = History.getInternetExplorerMajorVersion.cached =
189 (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
190 ? History.getInternetExplorerMajorVersion.cached
193 div = window.document.createElement('div'),
194 all = div.getElementsByTagName('i');
195 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
196 return (v > 4) ? v : false;
203 * History.isInternetExplorer()
204 * Are we using Internet Explorer?
206 * @license Public Domain
207 * @author Benjamin Arthur Lupton <contact@balupton.com>
209 History.isInternetExplorer = function(){
211 History.isInternetExplorer.cached =
212 (typeof History.isInternetExplorer.cached !== 'undefined')
213 ? History.isInternetExplorer.cached
214 : Boolean(History.getInternetExplorerMajorVersion())
221 * Which features require emulating?
224 if (History.options.html4Mode) {
235 window.history && window.history.pushState && window.history.replaceState
237 (/ 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) */
238 || (/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 */
242 !(('onhashchange' in window) || ('onhashchange' in window.document))
244 (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
251 * Is History enabled?
253 History.enabled = !History.emulated.pushState;
257 * Which bugs are present
261 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
262 * https://bugs.webkit.org/show_bug.cgi?id=56249
264 setHash: Boolean(!History.emulated.pushState && window.navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(window.navigator.userAgent)),
267 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
268 * https://bugs.webkit.org/show_bug.cgi?id=42940
270 safariPoll: Boolean(!History.emulated.pushState && window.navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(window.navigator.userAgent)),
273 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
275 ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
278 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
280 hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
284 * History.isEmptyObject(obj)
285 * Checks to see if the Object is Empty
286 * @param {Object} obj
289 History.isEmptyObject = function(obj) {
290 for ( var name in obj ) {
291 if ( obj.hasOwnProperty(name) ) {
299 * History.cloneObject(obj)
300 * Clones a object and eliminate all references to the original contexts
301 * @param {Object} obj
304 History.cloneObject = function(obj) {
307 hash = JSON.stringify(obj);
308 newObj = JSON.parse(hash);
317 // ====================================================================
321 * History.getRootUrl()
322 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
323 * @return {String} rootUrl
325 History.getRootUrl = function(){
327 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
328 if ( window.document.location.port||false ) {
329 rootUrl += ':'+window.document.location.port;
338 * History.getBaseHref()
339 * Fetches the `href` attribute of the `<base href="...">` element if it exists
340 * @return {String} baseHref
342 History.getBaseHref = function(){
345 baseElements = window.document.getElementsByTagName('base'),
349 // Test for Base Element
350 if ( baseElements.length === 1 ) {
351 // Prepare for Base Element
352 baseElement = baseElements[0];
353 baseHref = baseElement.href.replace(/[^\/]+$/,'');
356 // Adjust trailing slash
357 baseHref = baseHref.replace(/\/+$/,'');
358 if ( baseHref ) baseHref += '/';
365 * History.getBaseUrl()
366 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
367 * @return {String} baseUrl
369 History.getBaseUrl = function(){
371 var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
378 * History.getPageUrl()
379 * Fetches the URL of the current page
380 * @return {String} pageUrl
382 History.getPageUrl = function(){
385 State = History.getState(false,false),
386 stateUrl = (State||{}).url||History.getLocationHref(),
390 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
391 return (/\./).test(part) ? part : part+'/';
399 * History.getBasePageUrl()
400 * Fetches the Url of the directory of the current page
401 * @return {String} basePageUrl
403 History.getBasePageUrl = function(){
405 var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
406 return (/[^\/]$/).test(part) ? '' : part;
407 }).replace(/\/+$/,'')+'/';
414 * History.getFullUrl(url)
415 * Ensures that we have an absolute URL and not a relative URL
416 * @param {string} url
417 * @param {Boolean} allowBaseHref
418 * @return {string} fullUrl
420 History.getFullUrl = function(url,allowBaseHref){
422 var fullUrl = url, firstChar = url.substring(0,1);
423 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
426 if ( /[a-z]+\:\/\//.test(url) ) {
429 else if ( firstChar === '/' ) {
431 fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
433 else if ( firstChar === '#' ) {
435 fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
437 else if ( firstChar === '?' ) {
439 fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
443 if ( allowBaseHref ) {
444 fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
446 fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
448 // We have an if condition above as we do not want hashes
449 // which are relative to the baseHref in our URLs
450 // as if the baseHref changes, then all our bookmarks
451 // would now point to different locations
452 // whereas the basePageUrl will always stay the same
456 return fullUrl.replace(/\#$/,'');
460 * History.getShortUrl(url)
461 * Ensures that we have a relative URL and not a absolute URL
462 * @param {string} url
463 * @return {string} url
465 History.getShortUrl = function(url){
467 var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
470 if ( History.emulated.pushState ) {
471 // We are in a if statement as when pushState is not emulated
472 // The actual url these short urls are relative to can change
473 // So within the same session, we the url may end up somewhere different
474 shortUrl = shortUrl.replace(baseUrl,'');
478 shortUrl = shortUrl.replace(rootUrl,'/');
480 // Ensure we can still detect it as a state
481 if ( History.isTraditionalAnchor(shortUrl) ) {
482 shortUrl = './'+shortUrl;
486 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
493 * History.getLocationHref(document)
494 * Returns a normalized version of document.location.href
495 * accounting for browser inconsistencies, etc.
497 * This URL will be URI-encoded and will include the hash
499 * @param {object} document
500 * @return {string} url
502 History.getLocationHref = function(doc) {
503 doc = doc || window.document;
505 // most of the time, this will be true
506 if (doc.URL === doc.location.href)
507 return doc.location.href;
509 // some versions of webkit URI-decode document.location.href
510 // but they leave document.URL in an encoded state
511 if (doc.location.href === decodeURIComponent(doc.URL))
514 // FF 3.6 only updates document.URL when a page is reloaded
515 // document.location.href is updated correctly
516 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
517 return doc.location.href;
519 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
520 return doc.location.href;
522 return doc.URL || doc.location.href;
526 // ====================================================================
531 * The store for all session specific data
537 * 1-1: State ID to State Object
539 History.idToState = History.idToState||{};
543 * 1-1: State String to State ID
545 History.stateToId = History.stateToId||{};
549 * 1-1: State URL to State ID
551 History.urlToId = History.urlToId||{};
554 * History.storedStates
555 * Store the states in an array
557 History.storedStates = History.storedStates||[];
560 * History.savedStates
561 * Saved the states in an array
563 History.savedStates = History.savedStates||[];
566 * History.noramlizeStore()
567 * Noramlize the store by adding necessary values
569 History.normalizeStore = function(){
570 History.store.idToState = History.store.idToState||{};
571 History.store.urlToId = History.store.urlToId||{};
572 History.store.stateToId = History.store.stateToId||{};
577 * Get an object containing the data, title and url of the current state
578 * @param {Boolean} friendly
579 * @param {Boolean} create
580 * @return {Object} State
582 History.getState = function(friendly,create){
584 if ( typeof friendly === 'undefined' ) { friendly = true; }
585 if ( typeof create === 'undefined' ) { create = true; }
588 var State = History.getLastSavedState();
591 if ( !State && create ) {
592 State = History.createStateObject();
597 State = History.cloneObject(State);
598 State.url = State.cleanUrl||State.url;
606 * History.getIdByState(State)
607 * Gets a ID for a State
608 * @param {State} newState
609 * @return {String} id
611 History.getIdByState = function(newState){
614 var id = History.extractId(newState.url),
618 // Find ID via State String
619 str = History.getStateString(newState);
620 if ( typeof History.stateToId[str] !== 'undefined' ) {
621 id = History.stateToId[str];
623 else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
624 id = History.store.stateToId[str];
629 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
630 if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
635 // Apply the new State to the ID
636 History.stateToId[str] = id;
637 History.idToState[id] = newState;
646 * History.normalizeState(State)
647 * Expands a State Object
648 * @param {object} State
651 History.normalizeState = function(oldState){
653 var newState, dataNotEmpty;
656 if ( !oldState || (typeof oldState !== 'object') ) {
661 if ( typeof oldState.normalized !== 'undefined' ) {
666 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
670 // ----------------------------------------------------------------
674 newState.normalized = true;
675 newState.title = oldState.title||'';
676 newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
677 newState.hash = History.getShortUrl(newState.url);
678 newState.data = History.cloneObject(oldState.data);
681 newState.id = History.getIdByState(newState);
683 // ----------------------------------------------------------------
686 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
687 newState.url = newState.cleanUrl;
689 // Check to see if we have more than just a url
690 dataNotEmpty = !History.isEmptyObject(newState.data);
693 if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
695 newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
696 if ( !/\?/.test(newState.hash) ) {
697 newState.hash += '?';
699 newState.hash += '&_suid='+newState.id;
702 // Create the Hashed URL
703 newState.hashedUrl = History.getFullUrl(newState.hash);
705 // ----------------------------------------------------------------
707 // Update the URL if we have a duplicate
708 if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
709 newState.url = newState.hashedUrl;
712 // ----------------------------------------------------------------
719 * History.createStateObject(data,title,url)
720 * Creates a object based on the data, title and url state params
721 * @param {object} data
722 * @param {string} title
723 * @param {string} url
726 History.createStateObject = function(data,title,url){
735 State = History.normalizeState(State);
742 * History.getStateById(id)
743 * Get a state by it's UID
746 History.getStateById = function(id){
751 var State = History.idToState[id] || History.store.idToState[id] || undefined;
758 * Get a State's String
759 * @param {State} passedState
761 History.getStateString = function(passedState){
763 var State, cleanedState, str;
766 State = History.normalizeState(passedState);
771 title: passedState.title,
776 str = JSON.stringify(cleanedState);
784 * @param {State} passedState
785 * @return {String} id
787 History.getStateId = function(passedState){
792 State = History.normalizeState(passedState);
802 * History.getHashByState(State)
803 * Creates a Hash for the State Object
804 * @param {State} passedState
805 * @return {String} hash
807 History.getHashByState = function(passedState){
812 State = History.normalizeState(passedState);
822 * History.extractId(url_or_hash)
823 * Get a State ID by it's URL or Hash
824 * @param {string} url_or_hash
825 * @return {string} id
827 History.extractId = function ( url_or_hash ) {
829 var id,parts,url, tmp;
833 // If the URL has a #, use the id from before the #
834 if (url_or_hash.indexOf('#') != -1)
836 tmp = url_or_hash.split("#")[0];
843 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
844 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
845 id = parts ? String(parts[2]||'') : '';
852 * History.isTraditionalAnchor
853 * Checks to see if the url is a traditional anchor or not
854 * @param {String} url_or_hash
857 History.isTraditionalAnchor = function(url_or_hash){
859 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
862 return isTraditional;
866 * History.extractState
867 * Get a State by it's URL or Hash
868 * @param {String} url_or_hash
869 * @return {State|null}
871 History.extractState = function(url_or_hash,create){
873 var State = null, id, url;
874 create = create||false;
877 id = History.extractId(url_or_hash);
879 State = History.getStateById(id);
882 // Fetch SUID returned no State
885 url = History.getFullUrl(url_or_hash);
888 id = History.getIdByUrl(url)||false;
890 State = History.getStateById(id);
894 if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
895 State = History.createStateObject(null,null,url);
904 * History.getIdByUrl()
905 * Get a State ID by a State URL
907 History.getIdByUrl = function(url){
909 var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
916 * History.getLastSavedState()
917 * Get an object containing the data, title and url of the current state
918 * @return {Object} State
920 History.getLastSavedState = function(){
921 return History.savedStates[History.savedStates.length-1]||undefined;
925 * History.getLastStoredState()
926 * Get an object containing the data, title and url of the current state
927 * @return {Object} State
929 History.getLastStoredState = function(){
930 return History.storedStates[History.storedStates.length-1]||undefined;
934 * History.hasUrlDuplicate
935 * Checks if a Url will have a url conflict
936 * @param {Object} newState
937 * @return {Boolean} hasDuplicate
939 History.hasUrlDuplicate = function(newState) {
941 var hasDuplicate = false,
945 oldState = History.extractState(newState.url);
948 hasDuplicate = oldState && oldState.id !== newState.id;
957 * @param {Object} newState
958 * @return {Object} newState
960 History.storeState = function(newState){
962 History.urlToId[newState.url] = newState.id;
965 History.storedStates.push(History.cloneObject(newState));
972 * History.isLastSavedState(newState)
973 * Tests to see if the state is the last state
974 * @param {Object} newState
975 * @return {boolean} isLast
977 History.isLastSavedState = function(newState){
980 newId, oldState, oldId;
983 if ( History.savedStates.length ) {
985 oldState = History.getLastSavedState();
989 isLast = (newId === oldId);
999 * @param {Object} newState
1000 * @return {boolean} changed
1002 History.saveState = function(newState){
1004 if ( History.isLastSavedState(newState) ) {
1009 History.savedStates.push(History.cloneObject(newState));
1016 * History.getStateByIndex()
1017 * Gets a state by the index
1018 * @param {integer} index
1021 History.getStateByIndex = function(index){
1026 if ( typeof index === 'undefined' ) {
1027 // Get the last inserted
1028 State = History.savedStates[History.savedStates.length-1];
1030 else if ( index < 0 ) {
1032 State = History.savedStates[History.savedStates.length+index];
1035 // Get from the beginning
1036 State = History.savedStates[index];
1044 * History.getCurrentIndex()
1045 * Gets the current index
1048 History.getCurrentIndex = function(){
1053 if(History.savedStates.length < 1) {
1057 index = History.savedStates.length-1;
1062 // ====================================================================
1067 * @param {Location=} location
1068 * Gets the current document hash
1069 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1072 History.getHash = function(doc){
1073 var url = History.getLocationHref(doc),
1075 hash = History.getHashByUrl(url);
1080 * History.unescapeHash()
1081 * normalize and Unescape a Hash
1082 * @param {String} hash
1085 History.unescapeHash = function(hash){
1087 var result = History.normalizeHash(hash);
1090 result = decodeURIComponent(result);
1097 * History.normalizeHash()
1098 * normalize a hash across browsers
1101 History.normalizeHash = function(hash){
1103 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1110 * History.setHash(hash)
1111 * Sets the document hash
1112 * @param {string} hash
1115 History.setHash = function(hash,queue){
1120 if ( queue !== false && History.busy() ) {
1121 // Wait + Push to Queue
1122 //History.debug('History.setHash: we must wait', arguments);
1125 callback: History.setHash,
1133 //History.debug('History.setHash: called',hash);
1135 // Make Busy + Continue
1138 // Check if hash is a state
1139 State = History.extractState(hash,true);
1140 if ( State && !History.emulated.pushState ) {
1141 // Hash is a state so skip the setHash
1142 //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1145 History.pushState(State.data,State.title,State.url,false);
1147 else if ( History.getHash() !== hash ) {
1148 // Hash is a proper hash, so apply it
1150 // Handle browser bugs
1151 if ( History.bugs.setHash ) {
1152 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1154 // Fetch the base page
1155 pageUrl = History.getPageUrl();
1157 // Safari hash apply
1158 History.pushState(null,null,pageUrl+'#'+hash,false);
1161 // Normal hash apply
1162 window.document.location.hash = hash;
1172 * normalize and Escape a Hash
1175 History.escapeHash = function(hash){
1177 var result = History.normalizeHash(hash);
1180 result = window.encodeURIComponent(result);
1183 if ( !History.bugs.hashEscape ) {
1184 // Restore common parts
1186 .replace(/\%21/g,'!')
1187 .replace(/\%26/g,'&')
1188 .replace(/\%3D/g,'=')
1189 .replace(/\%3F/g,'?');
1197 * History.getHashByUrl(url)
1198 * Extracts the Hash from a URL
1199 * @param {string} url
1200 * @return {string} url
1202 History.getHashByUrl = function(url){
1204 var hash = String(url)
1205 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1209 hash = History.unescapeHash(hash);
1216 * History.setTitle(title)
1217 * Applies the title to the document
1218 * @param {State} newState
1221 History.setTitle = function(newState){
1223 var title = newState.title,
1228 firstState = History.getStateByIndex(0);
1229 if ( firstState && firstState.url === newState.url ) {
1230 title = firstState.title||History.options.initialTitle;
1236 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1238 catch ( Exception ) { }
1239 window.document.title = title;
1246 // ====================================================================
1251 * The list of queues to use
1252 * First In, First Out
1254 History.queues = [];
1257 * History.busy(value)
1258 * @param {boolean} value [optional]
1259 * @return {boolean} busy
1261 History.busy = function(value){
1263 if ( typeof value !== 'undefined' ) {
1264 //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
1265 History.busy.flag = value;
1268 else if ( typeof History.busy.flag === 'undefined' ) {
1269 History.busy.flag = false;
1273 if ( !History.busy.flag ) {
1274 // Execute the next item in the queue
1275 window.clearTimeout(History.busy.timeout);
1276 var fireNext = function(){
1278 if ( History.busy.flag ) return;
1279 for ( i=History.queues.length-1; i >= 0; --i ) {
1280 queue = History.queues[i];
1281 if ( queue.length === 0 ) continue;
1282 item = queue.shift();
1283 History.fireQueueItem(item);
1284 History.busy.timeout = window.setTimeout(fireNext,History.options.busyDelay);
1287 History.busy.timeout = window.setTimeout(fireNext,History.options.busyDelay);
1291 return History.busy.flag;
1297 History.busy.flag = false;
1300 * History.fireQueueItem(item)
1302 * @param {Object} item
1303 * @return {Mixed} result
1305 History.fireQueueItem = function(item){
1306 return item.callback.apply(item.scope||History,item.args||[]);
1310 * History.pushQueue(callback,args)
1311 * Add an item to the queue
1312 * @param {Object} item [scope,callback,args,queue]
1314 History.pushQueue = function(item){
1315 // Prepare the queue
1316 History.queues[item.queue||0] = History.queues[item.queue||0]||[];
1319 History.queues[item.queue||0].push(item);
1326 * History.queue (item,queue), (func,queue), (func), (item)
1327 * Either firs the item now if not busy, or adds it to the queue
1329 History.queue = function(item,queue){
1331 if ( typeof item === 'function' ) {
1336 if ( typeof queue !== 'undefined' ) {
1341 if ( History.busy() ) {
1342 History.pushQueue(item);
1344 History.fireQueueItem(item);
1352 * History.clearQueue()
1355 History.clearQueue = function(){
1356 History.busy.flag = false;
1357 History.queues = [];
1362 // ====================================================================
1366 * History.stateChanged
1367 * States whether or not the state has changed since the last double check was initialised
1369 History.stateChanged = false;
1372 * History.doubleChecker
1373 * Contains the timeout used for the double checks
1375 History.doubleChecker = false;
1378 * History.doubleCheckComplete()
1379 * Complete a double check
1382 History.doubleCheckComplete = function(){
1384 History.stateChanged = true;
1387 History.doubleCheckClear();
1394 * History.doubleCheckClear()
1395 * Clear a double check
1398 History.doubleCheckClear = function(){
1400 if ( History.doubleChecker ) {
1401 window.clearTimeout(History.doubleChecker);
1402 History.doubleChecker = false;
1410 * History.doubleCheck()
1411 * Create a double check
1414 History.doubleCheck = function(tryAgain){
1416 History.stateChanged = false;
1417 History.doubleCheckClear();
1419 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1420 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1421 if ( History.bugs.ieDoubleCheck ) {
1423 History.doubleChecker = window.setTimeout(
1425 History.doubleCheckClear();
1426 if ( !History.stateChanged ) {
1427 //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1433 History.options.doubleCheckInterval
1442 // ====================================================================
1446 * History.safariStatePoll()
1447 * Poll the current state
1450 History.safariStatePoll = function(){
1453 // Get the Last State which has the new URL
1455 urlState = History.extractState(History.getLocationHref()),
1458 // Check for a difference
1459 if ( !History.isLastSavedState(urlState) ) {
1460 newState = urlState;
1466 // Check if we have a state with that url
1469 //History.debug('History.safariStatePoll: new');
1470 newState = History.createStateObject();
1473 // Apply the New State
1474 //History.debug('History.safariStatePoll: trigger');
1475 History.Adapter.trigger(window,'popstate');
1482 // ====================================================================
1486 * History.back(queue)
1487 * Send the browser history back one item
1488 * @param {Integer} queue [optional]
1490 History.back = function(queue){
1491 //History.debug('History.back: called', arguments);
1494 if ( queue !== false && History.busy() ) {
1495 // Wait + Push to Queue
1496 //History.debug('History.back: we must wait', arguments);
1499 callback: History.back,
1506 // Make Busy + Continue
1509 // Fix certain browser bugs that prevent the state from changing
1510 History.doubleCheck(function(){
1511 History.back(false);
1522 * History.forward(queue)
1523 * Send the browser history forward one item
1524 * @param {Integer} queue [optional]
1526 History.forward = function(queue){
1527 //History.debug('History.forward: called', arguments);
1530 if ( queue !== false && History.busy() ) {
1531 // Wait + Push to Queue
1532 //History.debug('History.forward: we must wait', arguments);
1535 callback: History.forward,
1542 // Make Busy + Continue
1545 // Fix certain browser bugs that prevent the state from changing
1546 History.doubleCheck(function(){
1547 History.forward(false);
1553 // End forward closure
1558 * History.go(index,queue)
1559 * Send the browser history back or forward index times
1560 * @param {Integer} queue [optional]
1562 History.go = function(index,queue){
1563 //History.debug('History.go: called', arguments);
1571 for ( i=1; i<=index; ++i ) {
1572 History.forward(queue);
1575 else if ( index < 0 ) {
1577 for ( i=-1; i>=index; --i ) {
1578 History.back(queue);
1582 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1590 // ====================================================================
1591 // HTML5 State Support
1593 // Non-Native pushState Implementation
1594 if ( History.emulated.pushState ) {
1596 * Provide Skeleton for HTML4 Browsers
1600 var emptyFunction = function(){};
1601 History.pushState = History.pushState||emptyFunction;
1602 History.replaceState = History.replaceState||emptyFunction;
1603 } // History.emulated.pushState
1605 // Native pushState Implementation
1608 * Use native HTML5 History API Implementation
1612 * History.onPopState(event,extra)
1613 * Refresh the Current State
1615 History.onPopState = function(event,extra){
1617 var stateId = false, newState = false, currentHash, currentState;
1619 // Reset the double check
1620 History.doubleCheckComplete();
1622 // Check for a Hash, and handle apporiatly
1623 currentHash = History.getHash();
1624 if ( currentHash ) {
1626 currentState = History.extractState(currentHash||History.getLocationHref(),true);
1627 if ( currentState ) {
1628 // We were able to parse it, it must be a State!
1629 // Let's forward to replaceState
1630 //History.debug('History.onPopState: state anchor', currentHash, currentState);
1631 History.replaceState(currentState.data, currentState.title, currentState.url, false);
1634 // Traditional Anchor
1635 //History.debug('History.onPopState: traditional anchor', currentHash);
1636 History.Adapter.trigger(window,'anchorchange');
1637 History.busy(false);
1640 // We don't care for hashes
1641 History.expectedStateId = false;
1646 stateId = History.Adapter.extractEventData('state',event,extra) || false;
1650 // Vanilla: Back/forward button was used
1651 newState = History.getStateById(stateId);
1653 else if ( History.expectedStateId ) {
1654 // Vanilla: A new state was pushed, and popstate was called manually
1655 newState = History.getStateById(History.expectedStateId);
1659 newState = History.extractState(History.getLocationHref());
1662 // The State did not exist in our store
1664 // Regenerate the State
1665 newState = History.createStateObject(null,null,History.getLocationHref());
1669 History.expectedStateId = false;
1671 // Check if we are the same state
1672 if ( History.isLastSavedState(newState) ) {
1673 // There has been no change (just the page's hash has finally propagated)
1674 //History.debug('History.onPopState: no change', newState, History.savedStates);
1675 History.busy(false);
1680 History.storeState(newState);
1681 History.saveState(newState);
1683 // Force update of the title
1684 History.setTitle(newState);
1687 History.Adapter.trigger(window,'statechange');
1688 History.busy(false);
1693 History.Adapter.bind(window,'popstate',History.onPopState);
1696 * History.pushState(data,title,url)
1697 * Add a new State to the history object, become it, and trigger onpopstate
1698 * We have to trigger for HTML4 compatibility
1699 * @param {object} data
1700 * @param {string} title
1701 * @param {string} url
1704 History.pushState = function(data,title,url,queue){
1705 //History.debug('History.pushState: called', arguments);
1708 if ( History.getHashByUrl(url) && History.emulated.pushState ) {
1709 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1713 if ( queue !== false && History.busy() ) {
1714 // Wait + Push to Queue
1715 //History.debug('History.pushState: we must wait', arguments);
1718 callback: History.pushState,
1725 // Make Busy + Continue
1728 // Create the newState
1729 var newState = History.createStateObject(data,title,url);
1732 if ( History.isLastSavedState(newState) ) {
1733 // Won't be a change
1734 History.busy(false);
1737 // Store the newState
1738 History.storeState(newState);
1739 History.expectedStateId = newState.id;
1741 // Push the newState
1742 history.pushState(newState.id,newState.title,newState.url);
1745 History.Adapter.trigger(window,'popstate');
1748 // End pushState closure
1753 * History.replaceState(data,title,url)
1754 * Replace the State and trigger onpopstate
1755 * We have to trigger for HTML4 compatibility
1756 * @param {object} data
1757 * @param {string} title
1758 * @param {string} url
1761 History.replaceState = function(data,title,url,queue){
1762 //History.debug('History.replaceState: called', arguments);
1765 if ( History.getHashByUrl(url) && History.emulated.pushState ) {
1766 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1770 if ( queue !== false && History.busy() ) {
1771 // Wait + Push to Queue
1772 //History.debug('History.replaceState: we must wait', arguments);
1775 callback: History.replaceState,
1782 // Make Busy + Continue
1785 // Create the newState
1786 var newState = History.createStateObject(data,title,url);
1789 if ( History.isLastSavedState(newState) ) {
1790 // Won't be a change
1791 History.busy(false);
1794 // Store the newState
1795 History.storeState(newState);
1796 History.expectedStateId = newState.id;
1798 // Push the newState
1799 history.replaceState(newState.id,newState.title,newState.url);
1802 History.Adapter.trigger(window,'popstate');
1805 // End replaceState closure
1809 } // !History.emulated.pushState
1812 // ====================================================================
1818 if ( sessionStorage ) {
1821 History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
1828 History.normalizeStore();
1833 History.normalizeStore();
1837 * Clear Intervals on exit to prevent memory leaks
1839 History.Adapter.bind(window,"unload",History.clearAllIntervals);
1842 * Create the initial State
1844 History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
1847 * Bind for Saving Store
1849 if ( sessionStorage ) {
1850 // When the page is closed
1851 History.onUnload = function(){
1853 var currentStore, item, currentStoreString;
1857 currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
1864 currentStore.idToState = currentStore.idToState || {};
1865 currentStore.urlToId = currentStore.urlToId || {};
1866 currentStore.stateToId = currentStore.stateToId || {};
1869 for ( item in History.idToState ) {
1870 if ( !History.idToState.hasOwnProperty(item) ) {
1873 currentStore.idToState[item] = History.idToState[item];
1875 for ( item in History.urlToId ) {
1876 if ( !History.urlToId.hasOwnProperty(item) ) {
1879 currentStore.urlToId[item] = History.urlToId[item];
1881 for ( item in History.stateToId ) {
1882 if ( !History.stateToId.hasOwnProperty(item) ) {
1885 currentStore.stateToId[item] = History.stateToId[item];
1889 History.store = currentStore;
1890 History.normalizeStore();
1892 // In Safari, going into Private Browsing mode causes the
1893 // Session Storage object to still exist but if you try and use
1894 // or set any property/function of it it throws the exception
1895 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
1896 // add something to storage that exceeded the quota." infinitely
1898 currentStoreString = JSON.stringify(currentStore);
1901 sessionStorage.setItem('History.store', currentStoreString);
1904 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
1905 if (sessionStorage.length) {
1906 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
1907 // removing/resetting the storage can work.
1908 sessionStorage.removeItem('History.store');
1909 sessionStorage.setItem('History.store', currentStoreString);
1911 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
1919 // For Internet Explorer
1920 History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
1922 // For Other Browsers
1923 History.Adapter.bind(window,'beforeunload',History.onUnload);
1924 History.Adapter.bind(window,'unload',History.onUnload);
1926 // Both are enabled for consistency
1929 // Non-Native pushState Implementation
1930 if ( !History.emulated.pushState ) {
1931 // Be aware, the following is only for native pushState implementations
1932 // If you are wanting to include something for all browsers
1933 // Then include it above this if block
1938 if ( History.bugs.safariPoll ) {
1939 History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
1943 * Ensure Cross Browser Compatibility
1945 if ( window.navigator.vendor === 'Apple Computer, Inc.' || (window.navigator.appCodeName||'') === 'Mozilla' ) {
1947 * Fix Safari HashChange Issue
1951 History.Adapter.bind(window,'hashchange',function(){
1952 History.Adapter.trigger(window,'popstate');
1956 if ( History.getHash() ) {
1957 History.Adapter.onDomLoad(function(){
1958 History.Adapter.trigger(window,'hashchange');
1963 } // !History.emulated.pushState
1966 }; // History.initCore
1968 // Try to Initialise History
1969 if (!History.options || !History.options.delayInit) {