I have an iframe inside a lightning component that calls window.top.postMessage("data", "*");.

When my lightning component loads it adds an event listener of message to listen to this post

window.addEventListener('message', triggerEvent, false)

The problem here is that, when you leave the Lightning component in mobile and you go back to it, a new event listener is added, so that means when the window.top.postMessage("data", "*"); event fires, it fires twice, and if you open up the lightning component again, it fires 3 times, then 4 and so on.

I do not want to remove this event listener once it fires because i need to keep it for the entirety of the lightning components life. I have also tried to remove the event listener once the component undrenders by over riding the unrender functin, and it doesnt work.

How can I have the event listener fire only once but also keep it?

  • 3
    Assuming you are adding the event listener in the init handler of your component, just a thought here: verify if an application event exists, if not then only add the event listener, and then fire the application event. Now, next time whenever the flow gets back in your component, the application event will exist and thus no more event listener will be added. Theoretically this sounds like it should work.
    – Jayant Das
    May 7 '19 at 18:21
  • There is no way to verify if it exist, the function you use its apparently not allowed within the lightning component context May 13 '19 at 15:54

The solution to this was having the function that the event listener binds to be a helper function.

window.addEventListener('message', helper.MyMethod, false);


MyMethod: function(event){
    // handle event listener here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.