admin管理员组文章数量:1330591
Have tried Below Code but its not destroying Popstate Event
.
Please help we with the example in which i can destroy the Popstate Event
based on the condition.
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();
}
});
Have tried Below Code but its not destroying Popstate Event
.
Please help we with the example in which i can destroy the Popstate Event
based on the condition.
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();
}
});
Share
Improve this question
asked Apr 8, 2019 at 12:39
Hardik ShimpiHardik Shimpi
4101 gold badge7 silver badges13 bronze badges
2 Answers
Reset to default 7In 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);
The second argument you pass to removeEventListener
has to be the function you want to remove.
You are passing a different function, which hasn't been registered as an event handler, so nothing happens.
Declare your event handler as a function with a reference you can reuse. Then use that reference for both removeEventListener
and 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);
本文标签: javascriptHow to destroy 39Popstate39 event listenerStack Overflow
版权声明:本文标题:javascript - How to destroy 'Popstate' event listener? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742252237a2440977.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论