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' ) {
143 // ========================================================================
147 initCore : function(options){
149 this.intervalList = [];
153 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
154 this.sessionStorage.setItem('TEST', '1');
155 this.sessionStorage.removeItem('TEST');
157 this.sessionStorage = false;
161 if ( typeof this.initCore.initialized !== 'undefined' ) {
166 this.initCore.initialized = true;
174 * History.clearAllIntervals
175 * Clears all setInterval instances.
177 clearAllIntervals: function()
179 var i, il = this.intervalList;
180 if (typeof il !== "undefined" && il !== null) {
181 for (i = 0; i < il.length; i++) {
182 clearInterval(il[i]);
184 this.intervalList = null;
189 // ====================================================================
193 * History.debugLog(message,...)
194 * Logs the passed arguments if debug enabled
196 debugLog : function()
198 if ( (this.debug||false) ) {
199 Roo.log.apply(History,arguments);
205 // ====================================================================
209 * History.getInternetExplorerMajorVersion()
210 * Get's the major version of Internet Explorer
212 * @license Public Domain
213 * @author Benjamin Arthur Lupton <contact@balupton.com>
214 * @author James Padolsey <https://gist.github.com/527683>
216 getInternetExplorerMajorVersion = function(){
217 var result = this.getInternetExplorerMajorVersion.cached =
218 (typeof this.getInternetExplorerMajorVersion.cached !== 'undefined')
219 ? this.getInternetExplorerMajorVersion.cached
222 div = window.document.createElement('div'),
223 all = div.getElementsByTagName('i');
224 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
225 return (v > 4) ? v : false;
232 * isInternetExplorer()
233 * Are we using Internet Explorer?
235 * @license Public Domain
236 * @author Benjamin Arthur Lupton <contact@balupton.com>
238 isInternetExplorer = function(){
240 this.isInternetExplorer.cached =
241 (typeof this.isInternetExplorer.cached !== 'undefined')
242 ? this.isInternetExplorer.cached
243 : Boolean(this.getInternetExplorerMajorVersion())
249 * Which features require emulating?
257 initEmulated : function()
261 if (this.html4Mode) {
267 this.emulated.pushState = !Boolean(
268 window.history && window.history.pushState && window.history.replaceState
270 (/ 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) */
271 || (/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 */
274 this.emulated.hashChange = Boolean(
275 !(('onhashchange' in window) || ('onhashchange' in window.document))
277 (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
284 * Is History enabled?
286 History.enabled = !History.emulated.pushState;
291 * History.isEmptyObject(obj)
292 * Checks to see if the Object is Empty
293 * @param {Object} obj
296 History.isEmptyObject = function(obj) {
297 for ( var name in obj ) {
298 if ( obj.hasOwnProperty(name) ) {
306 * History.cloneObject(obj)
307 * Clones a object and eliminate all references to the original contexts
308 * @param {Object} obj
311 History.cloneObject = function(obj) {
314 hash = JSON.stringify(obj);
315 newObj = JSON.parse(hash);
324 // ====================================================================
328 * History.getRootUrl()
329 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
330 * @return {String} rootUrl
332 History.getRootUrl = function(){
334 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
335 if ( window.document.location.port||false ) {
336 rootUrl += ':'+window.document.location.port;
345 * History.getBaseHref()
346 * Fetches the `href` attribute of the `<base href="...">` element if it exists
347 * @return {String} baseHref
349 History.getBaseHref = function(){
352 baseElements = window.document.getElementsByTagName('base'),
356 // Test for Base Element
357 if ( baseElements.length === 1 ) {
358 // Prepare for Base Element
359 baseElement = baseElements[0];
360 baseHref = baseElement.href.replace(/[^\/]+$/,'');
363 // Adjust trailing slash
364 baseHref = baseHref.replace(/\/+$/,'');
365 if ( baseHref ) baseHref += '/';
372 * History.getBaseUrl()
373 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
374 * @return {String} baseUrl
376 History.getBaseUrl = function(){
378 var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
385 * History.getPageUrl()
386 * Fetches the URL of the current page
387 * @return {String} pageUrl
389 History.getPageUrl = function(){
392 State = History.getState(false,false),
393 stateUrl = (State||{}).url||History.getLocationHref(),
397 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
398 return (/\./).test(part) ? part : part+'/';
406 * History.getBasePageUrl()
407 * Fetches the Url of the directory of the current page
408 * @return {String} basePageUrl
410 History.getBasePageUrl = function(){
412 var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
413 return (/[^\/]$/).test(part) ? '' : part;
414 }).replace(/\/+$/,'')+'/';
421 * History.getFullUrl(url)
422 * Ensures that we have an absolute URL and not a relative URL
423 * @param {string} url
424 * @param {Boolean} allowBaseHref
425 * @return {string} fullUrl
427 History.getFullUrl = function(url,allowBaseHref){
429 var fullUrl = url, firstChar = url.substring(0,1);
430 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
433 if ( /[a-z]+\:\/\//.test(url) ) {
436 else if ( firstChar === '/' ) {
438 fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
440 else if ( firstChar === '#' ) {
442 fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
444 else if ( firstChar === '?' ) {
446 fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
450 if ( allowBaseHref ) {
451 fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
453 fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
455 // We have an if condition above as we do not want hashes
456 // which are relative to the baseHref in our URLs
457 // as if the baseHref changes, then all our bookmarks
458 // would now point to different locations
459 // whereas the basePageUrl will always stay the same
463 return fullUrl.replace(/\#$/,'');
467 * History.getShortUrl(url)
468 * Ensures that we have a relative URL and not a absolute URL
469 * @param {string} url
470 * @return {string} url
472 History.getShortUrl = function(url){
474 var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
477 if ( History.emulated.pushState ) {
478 // We are in a if statement as when pushState is not emulated
479 // The actual url these short urls are relative to can change
480 // So within the same session, we the url may end up somewhere different
481 shortUrl = shortUrl.replace(baseUrl,'');
485 shortUrl = shortUrl.replace(rootUrl,'/');
487 // Ensure we can still detect it as a state
488 if ( History.isTraditionalAnchor(shortUrl) ) {
489 shortUrl = './'+shortUrl;
493 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
500 * History.getLocationHref(document)
501 * Returns a normalized version of document.location.href
502 * accounting for browser inconsistencies, etc.
504 * This URL will be URI-encoded and will include the hash
506 * @param {object} document
507 * @return {string} url
509 History.getLocationHref = function(doc) {
510 doc = doc || window.document;
512 // most of the time, this will be true
513 if (doc.URL === doc.location.href)
514 return doc.location.href;
516 // some versions of webkit URI-decode document.location.href
517 // but they leave document.URL in an encoded state
518 if (doc.location.href === decodeURIComponent(doc.URL))
521 // FF 3.6 only updates document.URL when a page is reloaded
522 // document.location.href is updated correctly
523 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
524 return doc.location.href;
526 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
527 return doc.location.href;
529 return doc.URL || doc.location.href;
533 // ====================================================================
538 * The store for all session specific data
544 * 1-1: State ID to State Object
546 History.idToState = History.idToState||{};
550 * 1-1: State String to State ID
552 History.stateToId = History.stateToId||{};
556 * 1-1: State URL to State ID
558 History.urlToId = History.urlToId||{};
561 * History.storedStates
562 * Store the states in an array
564 History.storedStates = History.storedStates||[];
567 * History.savedStates
568 * Saved the states in an array
570 History.savedStates = History.savedStates||[];
573 * History.noramlizeStore()
574 * Noramlize the store by adding necessary values
576 History.normalizeStore = function(){
577 History.store.idToState = History.store.idToState||{};
578 History.store.urlToId = History.store.urlToId||{};
579 History.store.stateToId = History.store.stateToId||{};
584 * Get an object containing the data, title and url of the current state
585 * @param {Boolean} friendly
586 * @param {Boolean} create
587 * @return {Object} State
589 History.getState = function(friendly,create){
591 if ( typeof friendly === 'undefined' ) { friendly = true; }
592 if ( typeof create === 'undefined' ) { create = true; }
595 var State = History.getLastSavedState();
598 if ( !State && create ) {
599 State = History.createStateObject();
604 State = History.cloneObject(State);
605 State.url = State.cleanUrl||State.url;
613 * History.getIdByState(State)
614 * Gets a ID for a State
615 * @param {State} newState
616 * @return {String} id
618 History.getIdByState = function(newState){
621 var id = History.extractId(newState.url),
625 // Find ID via State String
626 str = History.getStateString(newState);
627 if ( typeof History.stateToId[str] !== 'undefined' ) {
628 id = History.stateToId[str];
630 else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
631 id = History.store.stateToId[str];
636 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
637 if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
642 // Apply the new State to the ID
643 History.stateToId[str] = id;
644 History.idToState[id] = newState;
653 * History.normalizeState(State)
654 * Expands a State Object
655 * @param {object} State
658 History.normalizeState = function(oldState){
660 var newState, dataNotEmpty;
663 if ( !oldState || (typeof oldState !== 'object') ) {
668 if ( typeof oldState.normalized !== 'undefined' ) {
673 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
677 // ----------------------------------------------------------------
681 newState.normalized = true;
682 newState.title = oldState.title||'';
683 newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
684 newState.hash = History.getShortUrl(newState.url);
685 newState.data = History.cloneObject(oldState.data);
688 newState.id = History.getIdByState(newState);
690 // ----------------------------------------------------------------
693 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
694 newState.url = newState.cleanUrl;
696 // Check to see if we have more than just a url
697 dataNotEmpty = !History.isEmptyObject(newState.data);
700 if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
702 newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
703 if ( !/\?/.test(newState.hash) ) {
704 newState.hash += '?';
706 newState.hash += '&_suid='+newState.id;
709 // Create the Hashed URL
710 newState.hashedUrl = History.getFullUrl(newState.hash);
712 // ----------------------------------------------------------------
714 // Update the URL if we have a duplicate
715 if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
716 newState.url = newState.hashedUrl;
719 // ----------------------------------------------------------------
726 * History.createStateObject(data,title,url)
727 * Creates a object based on the data, title and url state params
728 * @param {object} data
729 * @param {string} title
730 * @param {string} url
733 History.createStateObject = function(data,title,url){
742 State = History.normalizeState(State);
749 * History.getStateById(id)
750 * Get a state by it's UID
753 History.getStateById = function(id){
758 var State = History.idToState[id] || History.store.idToState[id] || undefined;
765 * Get a State's String
766 * @param {State} passedState
768 History.getStateString = function(passedState){
770 var State, cleanedState, str;
773 State = History.normalizeState(passedState);
778 title: passedState.title,
783 str = JSON.stringify(cleanedState);
791 * @param {State} passedState
792 * @return {String} id
794 History.getStateId = function(passedState){
799 State = History.normalizeState(passedState);
809 * History.getHashByState(State)
810 * Creates a Hash for the State Object
811 * @param {State} passedState
812 * @return {String} hash
814 History.getHashByState = function(passedState){
819 State = History.normalizeState(passedState);
829 * History.extractId(url_or_hash)
830 * Get a State ID by it's URL or Hash
831 * @param {string} url_or_hash
832 * @return {string} id
834 History.extractId = function ( url_or_hash ) {
836 var id,parts,url, tmp;
840 // If the URL has a #, use the id from before the #
841 if (url_or_hash.indexOf('#') != -1)
843 tmp = url_or_hash.split("#")[0];
850 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
851 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
852 id = parts ? String(parts[2]||'') : '';
859 * History.isTraditionalAnchor
860 * Checks to see if the url is a traditional anchor or not
861 * @param {String} url_or_hash
864 History.isTraditionalAnchor = function(url_or_hash){
866 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
869 return isTraditional;
873 * History.extractState
874 * Get a State by it's URL or Hash
875 * @param {String} url_or_hash
876 * @return {State|null}
878 History.extractState = function(url_or_hash,create){
880 var State = null, id, url;
881 create = create||false;
884 id = History.extractId(url_or_hash);
886 State = History.getStateById(id);
889 // Fetch SUID returned no State
892 url = History.getFullUrl(url_or_hash);
895 id = History.getIdByUrl(url)||false;
897 State = History.getStateById(id);
901 if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
902 State = History.createStateObject(null,null,url);
911 * History.getIdByUrl()
912 * Get a State ID by a State URL
914 History.getIdByUrl = function(url){
916 var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
923 * History.getLastSavedState()
924 * Get an object containing the data, title and url of the current state
925 * @return {Object} State
927 History.getLastSavedState = function(){
928 return History.savedStates[History.savedStates.length-1]||undefined;
932 * History.getLastStoredState()
933 * Get an object containing the data, title and url of the current state
934 * @return {Object} State
936 History.getLastStoredState = function(){
937 return History.storedStates[History.storedStates.length-1]||undefined;
941 * History.hasUrlDuplicate
942 * Checks if a Url will have a url conflict
943 * @param {Object} newState
944 * @return {Boolean} hasDuplicate
946 History.hasUrlDuplicate = function(newState) {
948 var hasDuplicate = false,
952 oldState = History.extractState(newState.url);
955 hasDuplicate = oldState && oldState.id !== newState.id;
964 * @param {Object} newState
965 * @return {Object} newState
967 History.storeState = function(newState){
969 History.urlToId[newState.url] = newState.id;
972 History.storedStates.push(History.cloneObject(newState));
979 * History.isLastSavedState(newState)
980 * Tests to see if the state is the last state
981 * @param {Object} newState
982 * @return {boolean} isLast
984 History.isLastSavedState = function(newState){
987 newId, oldState, oldId;
990 if ( History.savedStates.length ) {
992 oldState = History.getLastSavedState();
996 isLast = (newId === oldId);
1006 * @param {Object} newState
1007 * @return {boolean} changed
1009 History.saveState = function(newState){
1011 if ( History.isLastSavedState(newState) ) {
1016 History.savedStates.push(History.cloneObject(newState));
1023 * History.getStateByIndex()
1024 * Gets a state by the index
1025 * @param {integer} index
1028 History.getStateByIndex = function(index){
1033 if ( typeof index === 'undefined' ) {
1034 // Get the last inserted
1035 State = History.savedStates[History.savedStates.length-1];
1037 else if ( index < 0 ) {
1039 State = History.savedStates[History.savedStates.length+index];
1042 // Get from the beginning
1043 State = History.savedStates[index];
1051 * History.getCurrentIndex()
1052 * Gets the current index
1055 History.getCurrentIndex = function(){
1060 if(History.savedStates.length < 1) {
1064 index = History.savedStates.length-1;
1069 // ====================================================================
1074 * @param {Location=} location
1075 * Gets the current document hash
1076 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1079 History.getHash = function(doc){
1080 var url = History.getLocationHref(doc),
1082 hash = History.getHashByUrl(url);
1087 * History.unescapeHash()
1088 * normalize and Unescape a Hash
1089 * @param {String} hash
1092 History.unescapeHash = function(hash){
1094 var result = History.normalizeHash(hash);
1097 result = decodeURIComponent(result);
1104 * History.normalizeHash()
1105 * normalize a hash across browsers
1108 History.normalizeHash = function(hash){
1110 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1117 * History.setHash(hash)
1118 * Sets the document hash
1119 * @param {string} hash
1122 History.setHash = function(hash,queue){
1127 if ( queue !== false && History.busy() ) {
1128 // Wait + Push to Queue
1129 //History.debug('History.setHash: we must wait', arguments);
1132 callback: History.setHash,
1140 //History.debug('History.setHash: called',hash);
1142 // Make Busy + Continue
1145 // Check if hash is a state
1146 State = History.extractState(hash,true);
1147 if ( State && !History.emulated.pushState ) {
1148 // Hash is a state so skip the setHash
1149 //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1152 History.pushState(State.data,State.title,State.url,false);
1154 else if ( History.getHash() !== hash ) {
1155 // Hash is a proper hash, so apply it
1157 // Handle browser bugs
1158 if ( History.bugs.setHash ) {
1159 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1161 // Fetch the base page
1162 pageUrl = History.getPageUrl();
1164 // Safari hash apply
1165 History.pushState(null,null,pageUrl+'#'+hash,false);
1168 // Normal hash apply
1169 window.document.location.hash = hash;
1179 * normalize and Escape a Hash
1182 History.escapeHash = function(hash){
1184 var result = History.normalizeHash(hash);
1187 result = window.encodeURIComponent(result);
1190 if ( !History.bugs.hashEscape ) {
1191 // Restore common parts
1193 .replace(/\%21/g,'!')
1194 .replace(/\%26/g,'&')
1195 .replace(/\%3D/g,'=')
1196 .replace(/\%3F/g,'?');
1204 * History.getHashByUrl(url)
1205 * Extracts the Hash from a URL
1206 * @param {string} url
1207 * @return {string} url
1209 History.getHashByUrl = function(url){
1211 var hash = String(url)
1212 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1216 hash = History.unescapeHash(hash);
1223 * History.setTitle(title)
1224 * Applies the title to the document
1225 * @param {State} newState
1228 History.setTitle = function(newState){
1230 var title = newState.title,
1235 firstState = History.getStateByIndex(0);
1236 if ( firstState && firstState.url === newState.url ) {
1237 title = firstState.title||History.options.initialTitle;
1243 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1245 catch ( Exception ) { }
1246 window.document.title = title;
1253 // ====================================================================
1258 * The list of queues to use
1259 * First In, First Out
1261 History.queues = [];
1264 * History.busy(value)
1265 * @param {boolean} value [optional]
1266 * @return {boolean} busy
1268 History.busy = function(value){
1270 if ( typeof value !== 'undefined' ) {
1271 //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
1272 History.busy.flag = value;
1275 else if ( typeof History.busy.flag === 'undefined' ) {
1276 History.busy.flag = false;
1280 if ( !History.busy.flag ) {
1281 // Execute the next item in the queue
1282 window.clearTimeout(History.busy.timeout);
1283 var fireNext = function(){
1285 if ( History.busy.flag ) return;
1286 for ( i=History.queues.length-1; i >= 0; --i ) {
1287 queue = History.queues[i];
1288 if ( queue.length === 0 ) continue;
1289 item = queue.shift();
1290 History.fireQueueItem(item);
1291 History.busy.timeout = window.setTimeout(fireNext,History.options.busyDelay);
1294 History.busy.timeout = window.setTimeout(fireNext,History.options.busyDelay);
1298 return History.busy.flag;
1304 History.busy.flag = false;
1307 * History.fireQueueItem(item)
1309 * @param {Object} item
1310 * @return {Mixed} result
1312 History.fireQueueItem = function(item){
1313 return item.callback.apply(item.scope||History,item.args||[]);
1317 * History.pushQueue(callback,args)
1318 * Add an item to the queue
1319 * @param {Object} item [scope,callback,args,queue]
1321 History.pushQueue = function(item){
1322 // Prepare the queue
1323 History.queues[item.queue||0] = History.queues[item.queue||0]||[];
1326 History.queues[item.queue||0].push(item);
1333 * History.queue (item,queue), (func,queue), (func), (item)
1334 * Either firs the item now if not busy, or adds it to the queue
1336 History.queue = function(item,queue){
1338 if ( typeof item === 'function' ) {
1343 if ( typeof queue !== 'undefined' ) {
1348 if ( History.busy() ) {
1349 History.pushQueue(item);
1351 History.fireQueueItem(item);
1359 * History.clearQueue()
1362 History.clearQueue = function(){
1363 History.busy.flag = false;
1364 History.queues = [];
1369 // ====================================================================
1373 * History.stateChanged
1374 * States whether or not the state has changed since the last double check was initialised
1376 History.stateChanged = false;
1379 * History.doubleChecker
1380 * Contains the timeout used for the double checks
1382 History.doubleChecker = false;
1385 * History.doubleCheckComplete()
1386 * Complete a double check
1389 History.doubleCheckComplete = function(){
1391 History.stateChanged = true;
1394 History.doubleCheckClear();
1401 * History.doubleCheckClear()
1402 * Clear a double check
1405 History.doubleCheckClear = function(){
1407 if ( History.doubleChecker ) {
1408 window.clearTimeout(History.doubleChecker);
1409 History.doubleChecker = false;
1417 * History.doubleCheck()
1418 * Create a double check
1421 History.doubleCheck = function(tryAgain){
1423 History.stateChanged = false;
1424 History.doubleCheckClear();
1426 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1427 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1428 if ( History.bugs.ieDoubleCheck ) {
1430 History.doubleChecker = window.setTimeout(
1432 History.doubleCheckClear();
1433 if ( !History.stateChanged ) {
1434 //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1440 History.options.doubleCheckInterval
1449 // ====================================================================
1453 * History.safariStatePoll()
1454 * Poll the current state
1457 History.safariStatePoll = function(){
1460 // Get the Last State which has the new URL
1462 urlState = History.extractState(History.getLocationHref()),
1465 // Check for a difference
1466 if ( !History.isLastSavedState(urlState) ) {
1467 newState = urlState;
1473 // Check if we have a state with that url
1476 //History.debug('History.safariStatePoll: new');
1477 newState = History.createStateObject();
1480 // Apply the New State
1481 //History.debug('History.safariStatePoll: trigger');
1482 History.Adapter.trigger(window,'popstate');
1489 // ====================================================================
1493 * History.back(queue)
1494 * Send the browser history back one item
1495 * @param {Integer} queue [optional]
1497 History.back = function(queue){
1498 //History.debug('History.back: called', arguments);
1501 if ( queue !== false && History.busy() ) {
1502 // Wait + Push to Queue
1503 //History.debug('History.back: we must wait', arguments);
1506 callback: History.back,
1513 // Make Busy + Continue
1516 // Fix certain browser bugs that prevent the state from changing
1517 History.doubleCheck(function(){
1518 History.back(false);
1529 * History.forward(queue)
1530 * Send the browser history forward one item
1531 * @param {Integer} queue [optional]
1533 History.forward = function(queue){
1534 //History.debug('History.forward: called', arguments);
1537 if ( queue !== false && History.busy() ) {
1538 // Wait + Push to Queue
1539 //History.debug('History.forward: we must wait', arguments);
1542 callback: History.forward,
1549 // Make Busy + Continue
1552 // Fix certain browser bugs that prevent the state from changing
1553 History.doubleCheck(function(){
1554 History.forward(false);
1560 // End forward closure
1565 * History.go(index,queue)
1566 * Send the browser history back or forward index times
1567 * @param {Integer} queue [optional]
1569 History.go = function(index,queue){
1570 //History.debug('History.go: called', arguments);
1578 for ( i=1; i<=index; ++i ) {
1579 History.forward(queue);
1582 else if ( index < 0 ) {
1584 for ( i=-1; i>=index; --i ) {
1585 History.back(queue);
1589 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1597 // ====================================================================
1598 // HTML5 State Support
1600 // Non-Native pushState Implementation
1601 if ( History.emulated.pushState ) {
1603 * Provide Skeleton for HTML4 Browsers
1607 var emptyFunction = function(){};
1608 History.pushState = History.pushState||emptyFunction;
1609 History.replaceState = History.replaceState||emptyFunction;
1610 } // History.emulated.pushState
1612 // Native pushState Implementation
1615 * Use native HTML5 History API Implementation
1619 * History.onPopState(event,extra)
1620 * Refresh the Current State
1622 History.onPopState = function(event,extra){
1624 var stateId = false, newState = false, currentHash, currentState;
1626 // Reset the double check
1627 History.doubleCheckComplete();
1629 // Check for a Hash, and handle apporiatly
1630 currentHash = History.getHash();
1631 if ( currentHash ) {
1633 currentState = History.extractState(currentHash||History.getLocationHref(),true);
1634 if ( currentState ) {
1635 // We were able to parse it, it must be a State!
1636 // Let's forward to replaceState
1637 //History.debug('History.onPopState: state anchor', currentHash, currentState);
1638 History.replaceState(currentState.data, currentState.title, currentState.url, false);
1641 // Traditional Anchor
1642 //History.debug('History.onPopState: traditional anchor', currentHash);
1643 History.Adapter.trigger(window,'anchorchange');
1644 History.busy(false);
1647 // We don't care for hashes
1648 History.expectedStateId = false;
1653 stateId = History.Adapter.extractEventData('state',event,extra) || false;
1657 // Vanilla: Back/forward button was used
1658 newState = History.getStateById(stateId);
1660 else if ( History.expectedStateId ) {
1661 // Vanilla: A new state was pushed, and popstate was called manually
1662 newState = History.getStateById(History.expectedStateId);
1666 newState = History.extractState(History.getLocationHref());
1669 // The State did not exist in our store
1671 // Regenerate the State
1672 newState = History.createStateObject(null,null,History.getLocationHref());
1676 History.expectedStateId = false;
1678 // Check if we are the same state
1679 if ( History.isLastSavedState(newState) ) {
1680 // There has been no change (just the page's hash has finally propagated)
1681 //History.debug('History.onPopState: no change', newState, History.savedStates);
1682 History.busy(false);
1687 History.storeState(newState);
1688 History.saveState(newState);
1690 // Force update of the title
1691 History.setTitle(newState);
1694 History.Adapter.trigger(window,'statechange');
1695 History.busy(false);
1700 History.Adapter.bind(window,'popstate',History.onPopState);
1703 * History.pushState(data,title,url)
1704 * Add a new State to the history object, become it, and trigger onpopstate
1705 * We have to trigger for HTML4 compatibility
1706 * @param {object} data
1707 * @param {string} title
1708 * @param {string} url
1711 History.pushState = function(data,title,url,queue){
1712 //History.debug('History.pushState: called', arguments);
1715 if ( History.getHashByUrl(url) && History.emulated.pushState ) {
1716 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1720 if ( queue !== false && History.busy() ) {
1721 // Wait + Push to Queue
1722 //History.debug('History.pushState: we must wait', arguments);
1725 callback: History.pushState,
1732 // Make Busy + Continue
1735 // Create the newState
1736 var newState = History.createStateObject(data,title,url);
1739 if ( History.isLastSavedState(newState) ) {
1740 // Won't be a change
1741 History.busy(false);
1744 // Store the newState
1745 History.storeState(newState);
1746 History.expectedStateId = newState.id;
1748 // Push the newState
1749 history.pushState(newState.id,newState.title,newState.url);
1752 History.Adapter.trigger(window,'popstate');
1755 // End pushState closure
1760 * History.replaceState(data,title,url)
1761 * Replace the State and trigger onpopstate
1762 * We have to trigger for HTML4 compatibility
1763 * @param {object} data
1764 * @param {string} title
1765 * @param {string} url
1768 History.replaceState = function(data,title,url,queue){
1769 //History.debug('History.replaceState: called', arguments);
1772 if ( History.getHashByUrl(url) && History.emulated.pushState ) {
1773 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1777 if ( queue !== false && History.busy() ) {
1778 // Wait + Push to Queue
1779 //History.debug('History.replaceState: we must wait', arguments);
1782 callback: History.replaceState,
1789 // Make Busy + Continue
1792 // Create the newState
1793 var newState = History.createStateObject(data,title,url);
1796 if ( History.isLastSavedState(newState) ) {
1797 // Won't be a change
1798 History.busy(false);
1801 // Store the newState
1802 History.storeState(newState);
1803 History.expectedStateId = newState.id;
1805 // Push the newState
1806 history.replaceState(newState.id,newState.title,newState.url);
1809 History.Adapter.trigger(window,'popstate');
1812 // End replaceState closure
1816 } // !History.emulated.pushState
1819 // ====================================================================
1825 if ( sessionStorage ) {
1828 History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
1835 History.normalizeStore();
1840 History.normalizeStore();
1844 * Clear Intervals on exit to prevent memory leaks
1846 History.Adapter.bind(window,"unload",History.clearAllIntervals);
1849 * Create the initial State
1851 History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
1854 * Bind for Saving Store
1856 if ( sessionStorage ) {
1857 // When the page is closed
1858 History.onUnload = function(){
1860 var currentStore, item, currentStoreString;
1864 currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
1871 currentStore.idToState = currentStore.idToState || {};
1872 currentStore.urlToId = currentStore.urlToId || {};
1873 currentStore.stateToId = currentStore.stateToId || {};
1876 for ( item in History.idToState ) {
1877 if ( !History.idToState.hasOwnProperty(item) ) {
1880 currentStore.idToState[item] = History.idToState[item];
1882 for ( item in History.urlToId ) {
1883 if ( !History.urlToId.hasOwnProperty(item) ) {
1886 currentStore.urlToId[item] = History.urlToId[item];
1888 for ( item in History.stateToId ) {
1889 if ( !History.stateToId.hasOwnProperty(item) ) {
1892 currentStore.stateToId[item] = History.stateToId[item];
1896 History.store = currentStore;
1897 History.normalizeStore();
1899 // In Safari, going into Private Browsing mode causes the
1900 // Session Storage object to still exist but if you try and use
1901 // or set any property/function of it it throws the exception
1902 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
1903 // add something to storage that exceeded the quota." infinitely
1905 currentStoreString = JSON.stringify(currentStore);
1908 sessionStorage.setItem('History.store', currentStoreString);
1911 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
1912 if (sessionStorage.length) {
1913 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
1914 // removing/resetting the storage can work.
1915 sessionStorage.removeItem('History.store');
1916 sessionStorage.setItem('History.store', currentStoreString);
1918 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
1926 // For Internet Explorer
1927 History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
1929 // For Other Browsers
1930 History.Adapter.bind(window,'beforeunload',History.onUnload);
1931 History.Adapter.bind(window,'unload',History.onUnload);
1933 // Both are enabled for consistency
1936 // Non-Native pushState Implementation
1937 if ( !History.emulated.pushState ) {
1938 // Be aware, the following is only for native pushState implementations
1939 // If you are wanting to include something for all browsers
1940 // Then include it above this if block
1945 if ( History.bugs.safariPoll ) {
1946 History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
1950 * Ensure Cross Browser Compatibility
1952 if ( window.navigator.vendor === 'Apple Computer, Inc.' || (window.navigator.appCodeName||'') === 'Mozilla' ) {
1954 * Fix Safari HashChange Issue
1958 History.Adapter.bind(window,'hashchange',function(){
1959 History.Adapter.trigger(window,'popstate');
1963 if ( History.getHash() ) {
1964 History.Adapter.onDomLoad(function(){
1965 History.Adapter.trigger(window,'hashchange');
1970 } // !History.emulated.pushState
1973 }; // History.initCore
1975 // Try to Initialise History
1976 if (!History.options || !History.options.delayInit) {