已经尝试了以下代码,但没有破坏Popstate Event
。
请帮助我们提供一个示例,其中我可以根据条件破坏Popstate Event
。
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event) {
if (true){
history.pushState(null, document.title, location.href);
console.log('Back Button Prevented');
} else {
window.removeEventListener('popstate', ()=> {
console.log('Go back');
}, true);
history.back();
}
});
答案 0 :(得分:2)
In order to remove a listener, you have to pass the listener function itself to removeEventListener()
.
Another problem in your code is that with the use of if (true)
, you'll never reach the else
block that is removing the listener. What you'll probably want to do is have a boolean variable outside of the listener that you change on the first call of the listener.
var backButtonPrevented = false;
history.pushState(null, document.title, location.href);
function popStateListener(event) {
if (backButtonPrevented === false){
history.pushState(null, document.title, location.href);
console.log('Back Button Prevented');
backButtonPrevented = true;
} else {
window.removeEventListener('popstate', popStateListener);
history.back();
}
}
window.addEventListener('popstate', popStateListener);
答案 1 :(得分:0)
您传递给removeEventListener
的第二个参数必须是您要删除的函数。
您正在传递 different 函数,该函数尚未注册为事件处理程序,因此什么也没发生。
使用可重用的引用将事件处理程序声明为一个函数。然后将该引用用于两者 removeEventListener
和addEventListener
。
history.pushState(null, document.title, location.href);
function myEventListener (event) {
if (true){
history.pushState(null, document.title, location.href);
console.log('Back Button Prevented');
} else {
window.removeEventListener('popstate', myEventListener);
history.back();
}
}
window.addEventListener('popstate', myEventListener);