-1

How can I remove the eventlistener when a page navigates to another page in a single page app?

I'm facing this issue when revisiting that page, not when eventlistener is called

if (window.addEventListener) {
  window.addEventListener("message", listenMessage, false);
  // console.log("false");
} else {
  window.attachEvent("onmessage", listenMessage);
  //console.log("true");
}
var listenMessage = function(msg) {
/**/
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
dhinesh
  • 1
  • 4
  • Possible duplicate of [JavaScript: remove event listener](https://stackoverflow.com/questions/4402287/javascript-remove-event-listener) – Serge K. Dec 07 '17 at 13:24
  • 1
    "_remove the `eventlistner` when a page navigates to another page_" You don't need to do anything, if you're closing the current document, all the listeners will be gone with that document. Or is this some kind of a single page app? – Teemu Dec 07 '17 at 13:29
  • Yes its single page using angularjs – dhinesh Dec 07 '17 at 13:50
  • How can i close that document because im using angularjs single page app – dhinesh Dec 07 '17 at 14:03

3 Answers3

1

Use removeEventListener to remove event listeners.

window.removeEventListener("message", listenMessage, false);

And detachEvent in case attachEvent is getting executed

cdoshi
  • 2,772
  • 1
  • 13
  • 20
0
window.removeEventListener("onmessage", listenMessage);
window.detachEvent("onmessage", listenerMessage); // For IE

For more information, read the docs:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/detachEvent

Artur Nista
  • 359
  • 1
  • 4
  • Actually im facing listener class added no of times when the page revisiting , so I want remove the listener when that page navigate to another page – dhinesh Dec 07 '17 at 13:32
0

I think you should use a Layout Page and ,your first page and other page should based on this Layout Page. After that you can describe a global variable Before navigation you should change this variable's value. Check your variable's value and use that method:

document.getElementById("Your_Element_Id").removeEventListener("Your_Listener", your Function);
  • Im using iframe in parent page ,have one action button when im click on the button in that child page at that time send message using window.parent.postMessage(status, '*'); and in parent page using addEventListener.to get message, but , im navigate to another page and again back revisting page two times listener message added.so how can i remove listener when click navigate to another page – dhinesh Dec 07 '17 at 13:46