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);