replaceState和pushState可以修改浏览器地址而不刷新界面,非常好用。但如果要实现浏览器的前进后退,页面也会变化,就需要对replaceState和pushState行为进行监听。此时,我们就得自己添加事件监听:
01 | const bindEventListener = function (type) { |
02 | const historyEvent = history[type]; |
04 | const newEvent = historyEvent.apply( this , arguments); |
05 | const e = new Event(type); |
06 | e.arguments = arguments; |
07 | window.dispatchEvent(e); |
11 | history.pushState = bindEventListener( 'pushState' ); |
12 | history.replaceState = bindEventListener( 'replaceState' ); |
这样就创建了2个全新的事件,事件名为pushState和replaceState,我们就可以在全局监听:
1 | window.addEventListener( 'replaceState' , function (e) { |
2 | console.log( 'THEY DID IT AGAIN! replaceState' ); |
4 | window.addEventListener( 'pushState' , function (e) { |
5 | console.log( 'THEY DID IT AGAIN! pushState' ); |
这样就可以监听到pushState和replaceState行为。