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
Add a ment  | 

2 Answers 2

Reset to default 7

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

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