代碼瀏覽器
window.location.hash='edit'
效果app
http://xxxx/#edit
經過hash改變了url,會觸發hashchange事件,只要監聽hashchange事件,就能捕獲到經過hash改變url的行爲。this
window.onhashchange=function(event){ console.log(event); } //或者 window.addEventListener('hashchange',function(event){ console.log(event); })
若是是history.back(),history.forward()、history.go()那麼會觸發popstate事件url
window.addEventListener('popstate', function(event) { console.log(event); })
可是,history.pushState()和history.replaceState()不會觸發popstate事件,因此須要本身手動增長事件spa
history.replaceState和pushState不會觸發popstate事件,那麼如何監聽這兩個行爲呢。能夠經過在方法裏面主動的去觸發popstate事件。另外一種就是在方法中建立一個新的全局事件。code
const _historyWrap = function(type) { const orig = history[type]; const e = new Event(type); return function() { const rv = orig.apply(this, arguments); e.arguments = arguments; window.dispatchEvent(e); return rv; }; }; history.pushState = _historyWrap('pushState'); history.replaceState = _historyWrap('replaceState');
window.addEventListener('pushState', function(e) { console.log('change pushState'); }); window.addEventListener('replaceState', function(e) { console.log('change replaceState'); });