OLD | NEW |
(Empty) | |
| 1 (function() { |
| 2 // Extend the <a> tag with the window.history API |
| 3 // http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#t
he-history-interface |
| 4 // |
| 5 // <a is="html5-history-anchor" |
| 6 // [href="/path"] |
| 7 // [pushstate] |
| 8 // [replacestate] |
| 9 // [back] |
| 10 // [forward] |
| 11 // [go[="0"]] |
| 12 // [title="New Page Title"] |
| 13 // [state="{'message':'New State!'}"] |
| 14 // [popstate]> |
| 15 // title</a> |
| 16 |
| 17 var HTML5HistoryAnchorElement = Object.create(HTMLAnchorElement.prototype); |
| 18 |
| 19 function historyAnchorEventListener(event) { |
| 20 // open in new tab |
| 21 if (event.ctrlKey || event.metaKey || event.which === 2) { |
| 22 return; |
| 23 } |
| 24 |
| 25 // pushstate |
| 26 if (this.hasAttribute('pushstate')) { |
| 27 window.history.pushState(JSON.parse(this.getAttribute('state')), this.getA
ttribute('title'), this.getAttribute('href')); |
| 28 event.preventDefault(); |
| 29 } |
| 30 |
| 31 // replacestate |
| 32 if (this.hasAttribute('replacestate')) { |
| 33 window.history.replaceState(JSON.parse(this.getAttribute('state')), this.g
etAttribute('title'), this.getAttribute('href')); |
| 34 event.preventDefault(); |
| 35 } |
| 36 |
| 37 // popstate |
| 38 if (this.hasAttribute('popstate')) { |
| 39 try { |
| 40 var popstateEvent = new PopStateEvent('popstate', { |
| 41 bubbles: false, |
| 42 cancelable: false, |
| 43 state: window.history.state |
| 44 }); |
| 45 |
| 46 if ('dispatchEvent_' in window) { |
| 47 // FireFox with polyfill |
| 48 window.dispatchEvent_(popstateEvent); |
| 49 } else { |
| 50 // normal |
| 51 window.dispatchEvent(popstateEvent); |
| 52 } |
| 53 } catch(error) { |
| 54 // Internet Explorer |
| 55 var fallbackEvent = document.createEvent('CustomEvent'); |
| 56 fallbackEvent.initCustomEvent('popstate', false, false, { state: window.
history.state }); |
| 57 window.dispatchEvent(fallbackEvent); |
| 58 } |
| 59 |
| 60 event.preventDefault(); |
| 61 } |
| 62 |
| 63 // go |
| 64 if (this.hasAttribute('go')) { |
| 65 var num = this.getAttribute('go'); |
| 66 if (num) { |
| 67 num = parseInt(num); |
| 68 } else { |
| 69 num = 0; |
| 70 } |
| 71 window.history.go(num); |
| 72 event.preventDefault(); |
| 73 } |
| 74 |
| 75 // back |
| 76 if (this.hasAttribute('back')) { |
| 77 window.history.back(); |
| 78 event.preventDefault(); |
| 79 } |
| 80 |
| 81 // forward |
| 82 if (this.hasAttribute('forward')) { |
| 83 window.history.forward(); |
| 84 event.preventDefault(); |
| 85 } |
| 86 } |
| 87 |
| 88 HTML5HistoryAnchorElement.createdCallback = function() { |
| 89 this.addEventListener('click', historyAnchorEventListener, false); |
| 90 }; |
| 91 |
| 92 document.registerElement('html5-history-anchor', { |
| 93 prototype: HTML5HistoryAnchorElement, |
| 94 extends: 'a' |
| 95 }); |
| 96 })(); |
OLD | NEW |