最近在做一個url變換的監測在網上查到h5的replaceState和pushState,擼了幾行代碼
window.addEventListener('replaceState', function (e) {
// 頁面切換url上報
pageChange(location.href);
})
window.addEventListener('pushState', function (e) {
// 頁面切換url上報
pageChange(location.href);
})
然並卵,並沒有得到想要的結果,後來在網上查到一個函數。
// 重寫pushState與replaceState事件函數
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');
此時調用以上兩個監聽,就可以收集到url的變化信息了,你以爲這就結束了。。。並沒有
ie老祖宗不同意啊。。。
爲了兼容,ie中只能計時器,(消耗性能),爲減少消耗需判斷一下環境在使用以下代碼
var url = location.href
// 不支持則用定時器檢測的辦法
setInterval(function() {
if(url!=location.href){
url = location.href
pageChange(location.href)
}
}, 150);