Javascript 如何区分哈希(#)URL更改和其他URL更改?
我试图区分两种类型的URL更改 基本上,使用Javascript 如何区分哈希(#)URL更改和其他URL更改?,javascript,pushstate,Javascript,Pushstate,我试图区分两种类型的URL更改 基本上,使用pushstate可以从http://example.com至http://example.com/account无需重新加载页面(如下所示) 可以使用以下技巧检测这些变化(摘自[此处]( )): 不过,我意识到它还捕获哈希URL更改,例如http://example.com#about。我知道哈希URL更改可以通过以下方式捕获: $(window).bind('hashchange', function() { /* things */ });
pushstate
可以从http://example.com
至http://example.com/account
无需重新加载页面(如下所示)
可以使用以下技巧检测这些变化(摘自[此处](
)):
不过,我意识到它还捕获哈希URL更改,例如http://example.com#about
。我知道哈希URL更改可以通过以下方式捕获:
$(window).bind('hashchange', function() {
/* things */
});
我的问题是散列更改也会触发popstate
(在历史记录中)()
我该如何区分这两种类型的事件呢?我担心必须依赖正则表达式才能获得散列,但我刚刚意识到
位置
对象已经从URL解析散列
我所需要做的就是在事件前后从该位置捕获哈希(并保持更新)
因此,使用当前位置引入一个变量:
current_hash = window.location.hash;
并使用它来区分URL更改的类型(保持更新):
完整示例
current_hash = window.location.hash;
window.addEventListener('popstate', (ev) => {
if (ev.target.location.hash == current_hash){
window.dispatchEvent(new Event('locationchange'));
} else {
current_hash = ev.target.location.hash;
}
});
# variable that keeps the current hash
current_hash = window.location.hash;
history.pushState = ( f => function pushState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('pushState'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.pushState);
history.replaceState = ( f => function replaceState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('replaceState'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.replaceState);
window.addEventListener('popstate', (ev) => {
# use it to distinguish the event
if (ev.target.location.hash == current_hash){
window.dispatchEvent(new Event('locationchange'));
} else {
# keep current hash updated
current_hash = ev.target.location.hash;
}
});
window.addEventListener('locationchange', function(event){
console.log('location changed!');
})