history.html4.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. /**
  2. * History.js HTML4 Support
  3. * Depends on the HTML5 Support
  4. * @author Benjamin Arthur Lupton <contact@balupton.com>
  5. * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
  6. * @license New BSD License <http://creativecommons.org/licenses/BSD/>
  7. */
  8. (function(window,undefined){
  9. "use strict";
  10. // ========================================================================
  11. // Initialise
  12. // Localise Globals
  13. var
  14. document = window.document, // Make sure we are using the correct document
  15. setTimeout = window.setTimeout||setTimeout,
  16. clearTimeout = window.clearTimeout||clearTimeout,
  17. setInterval = window.setInterval||setInterval,
  18. History = window.History = window.History||{}; // Public History Object
  19. // Check Existence
  20. if ( typeof History.initHtml4 !== 'undefined' ) {
  21. throw new Error('History.js HTML4 Support has already been loaded...');
  22. }
  23. // ========================================================================
  24. // Initialise HTML4 Support
  25. // Initialise HTML4 Support
  26. History.initHtml4 = function(){
  27. // Initialise
  28. if ( typeof History.initHtml4.initialized !== 'undefined' ) {
  29. // Already Loaded
  30. return false;
  31. }
  32. else {
  33. History.initHtml4.initialized = true;
  34. }
  35. // ====================================================================
  36. // Properties
  37. /**
  38. * History.enabled
  39. * Is History enabled?
  40. */
  41. History.enabled = true;
  42. // ====================================================================
  43. // Hash Storage
  44. /**
  45. * History.savedHashes
  46. * Store the hashes in an array
  47. */
  48. History.savedHashes = [];
  49. /**
  50. * History.isLastHash(newHash)
  51. * Checks if the hash is the last hash
  52. * @param {string} newHash
  53. * @return {boolean} true
  54. */
  55. History.isLastHash = function(newHash){
  56. // Prepare
  57. var oldHash = History.getHashByIndex(),
  58. isLast;
  59. // Check
  60. isLast = newHash === oldHash;
  61. // Return isLast
  62. return isLast;
  63. };
  64. /**
  65. * History.saveHash(newHash)
  66. * Push a Hash
  67. * @param {string} newHash
  68. * @return {boolean} true
  69. */
  70. History.saveHash = function(newHash){
  71. // Check Hash
  72. if ( History.isLastHash(newHash) ) {
  73. return false;
  74. }
  75. // Push the Hash
  76. History.savedHashes.push(newHash);
  77. // Return true
  78. return true;
  79. };
  80. /**
  81. * History.getHashByIndex()
  82. * Gets a hash by the index
  83. * @param {integer} index
  84. * @return {string}
  85. */
  86. History.getHashByIndex = function(index){
  87. // Prepare
  88. var hash = null;
  89. // Handle
  90. if ( typeof index === 'undefined' ) {
  91. // Get the last inserted
  92. hash = History.savedHashes[History.savedHashes.length-1];
  93. }
  94. else if ( index < 0 ) {
  95. // Get from the end
  96. hash = History.savedHashes[History.savedHashes.length+index];
  97. }
  98. else {
  99. // Get from the beginning
  100. hash = History.savedHashes[index];
  101. }
  102. // Return hash
  103. return hash;
  104. };
  105. // ====================================================================
  106. // Discarded States
  107. /**
  108. * History.discardedHashes
  109. * A hashed array of discarded hashes
  110. */
  111. History.discardedHashes = {};
  112. /**
  113. * History.discardedStates
  114. * A hashed array of discarded states
  115. */
  116. History.discardedStates = {};
  117. /**
  118. * History.discardState(State)
  119. * Discards the state by ignoring it through History
  120. * @param {object} State
  121. * @return {true}
  122. */
  123. History.discardState = function(discardedState,forwardState,backState){
  124. //History.debug('History.discardState', arguments);
  125. // Prepare
  126. var discardedStateHash = History.getHashByState(discardedState),
  127. discardObject;
  128. // Create Discard Object
  129. discardObject = {
  130. 'discardedState': discardedState,
  131. 'backState': backState,
  132. 'forwardState': forwardState
  133. };
  134. // Add to DiscardedStates
  135. History.discardedStates[discardedStateHash] = discardObject;
  136. // Return true
  137. return true;
  138. };
  139. /**
  140. * History.discardHash(hash)
  141. * Discards the hash by ignoring it through History
  142. * @param {string} hash
  143. * @return {true}
  144. */
  145. History.discardHash = function(discardedHash,forwardState,backState){
  146. //History.debug('History.discardState', arguments);
  147. // Create Discard Object
  148. var discardObject = {
  149. 'discardedHash': discardedHash,
  150. 'backState': backState,
  151. 'forwardState': forwardState
  152. };
  153. // Add to discardedHash
  154. History.discardedHashes[discardedHash] = discardObject;
  155. // Return true
  156. return true;
  157. };
  158. /**
  159. * History.discardState(State)
  160. * Checks to see if the state is discarded
  161. * @param {object} State
  162. * @return {bool}
  163. */
  164. History.discardedState = function(State){
  165. // Prepare
  166. var StateHash = History.getHashByState(State),
  167. discarded;
  168. // Check
  169. discarded = History.discardedStates[StateHash]||false;
  170. // Return true
  171. return discarded;
  172. };
  173. /**
  174. * History.discardedHash(hash)
  175. * Checks to see if the state is discarded
  176. * @param {string} State
  177. * @return {bool}
  178. */
  179. History.discardedHash = function(hash){
  180. // Check
  181. var discarded = History.discardedHashes[hash]||false;
  182. // Return true
  183. return discarded;
  184. };
  185. /**
  186. * History.recycleState(State)
  187. * Allows a discarded state to be used again
  188. * @param {object} data
  189. * @param {string} title
  190. * @param {string} url
  191. * @return {true}
  192. */
  193. History.recycleState = function(State){
  194. //History.debug('History.recycleState', arguments);
  195. // Prepare
  196. var StateHash = History.getHashByState(State);
  197. // Remove from DiscardedStates
  198. if ( History.discardedState(State) ) {
  199. delete History.discardedStates[StateHash];
  200. }
  201. // Return true
  202. return true;
  203. };
  204. // ====================================================================
  205. // HTML4 HashChange Support
  206. if ( History.emulated.hashChange ) {
  207. /*
  208. * We must emulate the HTML4 HashChange Support by manually checking for hash changes
  209. */
  210. /**
  211. * History.hashChangeInit()
  212. * Init the HashChange Emulation
  213. */
  214. History.hashChangeInit = function(){
  215. // Define our Checker Function
  216. History.checkerFunction = null;
  217. // Define some variables that will help in our checker function
  218. var lastDocumentHash = '',
  219. iframeId, iframe,
  220. lastIframeHash, checkerRunning;
  221. // Handle depending on the browser
  222. if ( History.isInternetExplorer() ) {
  223. // IE6 and IE7
  224. // We need to use an iframe to emulate the back and forward buttons
  225. // Create iFrame
  226. iframeId = 'historyjs-iframe';
  227. iframe = document.createElement('iframe');
  228. // Adjust iFarme
  229. iframe.setAttribute('id', iframeId);
  230. iframe.style.display = 'none';
  231. // Append iFrame
  232. document.body.appendChild(iframe);
  233. // Create initial history entry
  234. iframe.contentWindow.document.open();
  235. iframe.contentWindow.document.close();
  236. // Define some variables that will help in our checker function
  237. lastIframeHash = '';
  238. checkerRunning = false;
  239. // Define the checker function
  240. History.checkerFunction = function(){
  241. // Check Running
  242. if ( checkerRunning ) {
  243. return false;
  244. }
  245. // Update Running
  246. checkerRunning = true;
  247. // Fetch
  248. var documentHash = History.getHash()||'',
  249. iframeHash = History.unescapeHash(iframe.contentWindow.document.location.hash)||'';
  250. // The Document Hash has changed (application caused)
  251. if ( documentHash !== lastDocumentHash ) {
  252. // Equalise
  253. lastDocumentHash = documentHash;
  254. // Create a history entry in the iframe
  255. if ( iframeHash !== documentHash ) {
  256. //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
  257. // Equalise
  258. lastIframeHash = iframeHash = documentHash;
  259. // Create History Entry
  260. iframe.contentWindow.document.open();
  261. iframe.contentWindow.document.close();
  262. // Update the iframe's hash
  263. iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
  264. }
  265. // Trigger Hashchange Event
  266. History.Adapter.trigger(window,'hashchange');
  267. }
  268. // The iFrame Hash has changed (back button caused)
  269. else if ( iframeHash !== lastIframeHash ) {
  270. //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
  271. // Equalise
  272. lastIframeHash = iframeHash;
  273. // Update the Hash
  274. History.setHash(iframeHash,false);
  275. }
  276. // Reset Running
  277. checkerRunning = false;
  278. // Return true
  279. return true;
  280. };
  281. }
  282. else {
  283. // We are not IE
  284. // Firefox 1 or 2, Opera
  285. // Define the checker function
  286. History.checkerFunction = function(){
  287. // Prepare
  288. var documentHash = History.getHash();
  289. // The Document Hash has changed (application caused)
  290. if ( documentHash !== lastDocumentHash ) {
  291. // Equalise
  292. lastDocumentHash = documentHash;
  293. // Trigger Hashchange Event
  294. History.Adapter.trigger(window,'hashchange');
  295. }
  296. // Return true
  297. return true;
  298. };
  299. }
  300. // Apply the checker function
  301. History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
  302. // Done
  303. return true;
  304. }; // History.hashChangeInit
  305. // Bind hashChangeInit
  306. History.Adapter.onDomLoad(History.hashChangeInit);
  307. } // History.emulated.hashChange
  308. // ====================================================================
  309. // HTML5 State Support
  310. // Non-Native pushState Implementation
  311. if ( History.emulated.pushState ) {
  312. /*
  313. * We must emulate the HTML5 State Management by using HTML4 HashChange
  314. */
  315. /**
  316. * History.onHashChange(event)
  317. * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
  318. */
  319. History.onHashChange = function(event){
  320. //History.debug('History.onHashChange', arguments);
  321. // Prepare
  322. var currentUrl = ((event && event.newURL) || document.location.href),
  323. currentHash = History.getHashByUrl(currentUrl),
  324. currentState = null,
  325. currentStateHash = null,
  326. currentStateHashExits = null,
  327. discardObject;
  328. // Check if we are the same state
  329. if ( History.isLastHash(currentHash) ) {
  330. // There has been no change (just the page's hash has finally propagated)
  331. //History.debug('History.onHashChange: no change');
  332. History.busy(false);
  333. return false;
  334. }
  335. // Reset the double check
  336. History.doubleCheckComplete();
  337. // Store our location for use in detecting back/forward direction
  338. History.saveHash(currentHash);
  339. // Expand Hash
  340. if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
  341. //History.debug('History.onHashChange: traditional anchor', currentHash);
  342. // Traditional Anchor Hash
  343. History.Adapter.trigger(window,'anchorchange');
  344. History.busy(false);
  345. return false;
  346. }
  347. // Create State
  348. currentState = History.extractState(History.getFullUrl(currentHash||document.location.href,false),true);
  349. // Check if we are the same state
  350. if ( History.isLastSavedState(currentState) ) {
  351. //History.debug('History.onHashChange: no change');
  352. // There has been no change (just the page's hash has finally propagated)
  353. History.busy(false);
  354. return false;
  355. }
  356. // Create the state Hash
  357. currentStateHash = History.getHashByState(currentState);
  358. // Check if we are DiscardedState
  359. discardObject = History.discardedState(currentState);
  360. if ( discardObject ) {
  361. // Ignore this state as it has been discarded and go back to the state before it
  362. if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
  363. // We are going backwards
  364. //History.debug('History.onHashChange: go backwards');
  365. History.back(false);
  366. } else {
  367. // We are going forwards
  368. //History.debug('History.onHashChange: go forwards');
  369. History.forward(false);
  370. }
  371. return false;
  372. }
  373. // Push the new HTML5 State
  374. //History.debug('History.onHashChange: success hashchange');
  375. History.pushState(currentState.data,currentState.title,currentState.url,false);
  376. // End onHashChange closure
  377. return true;
  378. };
  379. History.Adapter.bind(window,'hashchange',History.onHashChange);
  380. /**
  381. * History.pushState(data,title,url)
  382. * Add a new State to the history object, become it, and trigger onpopstate
  383. * We have to trigger for HTML4 compatibility
  384. * @param {object} data
  385. * @param {string} title
  386. * @param {string} url
  387. * @return {true}
  388. */
  389. History.pushState = function(data,title,url,queue){
  390. //History.debug('History.pushState: called', arguments);
  391. // Check the State
  392. if ( History.getHashByUrl(url) ) {
  393. throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
  394. }
  395. // Handle Queueing
  396. if ( queue !== false && History.busy() ) {
  397. // Wait + Push to Queue
  398. //History.debug('History.pushState: we must wait', arguments);
  399. History.pushQueue({
  400. scope: History,
  401. callback: History.pushState,
  402. args: arguments,
  403. queue: queue
  404. });
  405. return false;
  406. }
  407. // Make Busy
  408. History.busy(true);
  409. // Fetch the State Object
  410. var newState = History.createStateObject(data,title,url),
  411. newStateHash = History.getHashByState(newState),
  412. oldState = History.getState(false),
  413. oldStateHash = History.getHashByState(oldState),
  414. html4Hash = History.getHash();
  415. // Store the newState
  416. History.storeState(newState);
  417. History.expectedStateId = newState.id;
  418. // Recycle the State
  419. History.recycleState(newState);
  420. // Force update of the title
  421. History.setTitle(newState);
  422. // Check if we are the same State
  423. if ( newStateHash === oldStateHash ) {
  424. //History.debug('History.pushState: no change', newStateHash);
  425. History.busy(false);
  426. return false;
  427. }
  428. // Update HTML4 Hash
  429. if ( newStateHash !== html4Hash && newStateHash !== History.getShortUrl(document.location.href) ) {
  430. //History.debug('History.pushState: update hash', newStateHash, html4Hash);
  431. History.setHash(newStateHash,false);
  432. return false;
  433. }
  434. // Update HTML5 State
  435. History.saveState(newState);
  436. // Fire HTML5 Event
  437. //History.debug('History.pushState: trigger popstate');
  438. History.Adapter.trigger(window,'statechange');
  439. History.busy(false);
  440. // End pushState closure
  441. return true;
  442. };
  443. /**
  444. * History.replaceState(data,title,url)
  445. * Replace the State and trigger onpopstate
  446. * We have to trigger for HTML4 compatibility
  447. * @param {object} data
  448. * @param {string} title
  449. * @param {string} url
  450. * @return {true}
  451. */
  452. History.replaceState = function(data,title,url,queue){
  453. //History.debug('History.replaceState: called', arguments);
  454. // Check the State
  455. if ( History.getHashByUrl(url) ) {
  456. throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
  457. }
  458. // Handle Queueing
  459. if ( queue !== false && History.busy() ) {
  460. // Wait + Push to Queue
  461. //History.debug('History.replaceState: we must wait', arguments);
  462. History.pushQueue({
  463. scope: History,
  464. callback: History.replaceState,
  465. args: arguments,
  466. queue: queue
  467. });
  468. return false;
  469. }
  470. // Make Busy
  471. History.busy(true);
  472. // Fetch the State Objects
  473. var newState = History.createStateObject(data,title,url),
  474. oldState = History.getState(false),
  475. previousState = History.getStateByIndex(-2);
  476. // Discard Old State
  477. History.discardState(oldState,newState,previousState);
  478. // Alias to PushState
  479. History.pushState(newState.data,newState.title,newState.url,false);
  480. // End replaceState closure
  481. return true;
  482. };
  483. } // History.emulated.pushState
  484. // ====================================================================
  485. // Initialise
  486. // Non-Native pushState Implementation
  487. if ( History.emulated.pushState ) {
  488. /**
  489. * Ensure initial state is handled correctly
  490. */
  491. if ( History.getHash() && !History.emulated.hashChange ) {
  492. History.Adapter.onDomLoad(function(){
  493. History.Adapter.trigger(window,'hashchange');
  494. });
  495. }
  496. } // History.emulated.pushState
  497. }; // History.initHtml4
  498. // Try and Initialise History
  499. if ( typeof History.init !== 'undefined' ) {
  500. History.init();
  501. }
  502. })(window);