慕運維8079593
2019-02-13 17:15:19
chrome 63,直接監(jiān)聽pushState事件無效:window.addEventListener("pushState", function () { // code });直接監(jiān)聽replaceState也是無效的,popstate有效。我搜索之后在jb51上找到了一個辦法,先添加一段代碼,再添加監(jiān)聽就可以了。var _wr = function(type) { var orig = history[type]; return function() { var rv = orig.apply(this, arguments); var e = new Event(type); e.arguments = arguments; window.dispatchEvent(e); return rv; };};history.pushState = _wr('pushState');history.replaceState = _wr('replaceState');那么為什么直接監(jiān)聽無效呢?是瀏覽器的問題還是什么原因?測試網(wǎng)址:pixiv 特輯(需要科學上網(wǎng)),從這個頁面進入子頁面用的就是pushState。
1 回答

慕俠2389804
TA貢獻1719條經(jīng)驗 獲得超6個贊
沒有onpushstate這個事件,當然無法監(jiān)聽到了。
可以把history劫持一下:
(function(history){
var pushState = history.pushState;
history.pushState = function(state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({state: state});
}
// ... whatever else you want to do
// maybe call onhashchange e.handler
return pushState.apply(history, arguments);
};
})(window.history);
history.onpushstate = function(e) {
console.log('pushed');
}
效果:
添加回答
舉報
0/150
提交
取消