react-native-web-community/react-native-web-webview

Event onMessage fired many times after the first event

adrianicv opened this issue · 6 comments

In the onMessage example, if the button is pressed, the message appears in the console as expected. But after that, all events captured by the WindowsListener are also printed in the console.

Steps to reproduce:

  1. Enter in the onMessage in the storybook example and press send message.
  2. Change to any other examples and you will see that each time you change of example a event is captured and printed in the console.

Moreover, each time you pressed the button, one more EventListener is activated. So, the number of messages increase "n" times, where "n" is the number of EventListener active.

Problem is at

if (props.onMessage) {
window.addEventListener('message', this.onMessage, true);
}
, the message listener is not unregistered on unload, that's why they are later captured and when loading several times messages get duplicated.

I think addEventListener() should be called instead on componentDidMount() and use removeEventListener() at componentWillUnmount().

Thanks for the feedback !
It should indeed be handled in componentDidMount / componentWillUnmount.
If you're feeling like doing a PR you're very welcome ! Otherwise I'll try to find some time next week :)

If you're feeling like doing a PR you're very welcome

Done.

Thanks a lot @piranna! This is fixed in v0.1.0.

Thanks a lot @piranna! This is fixed in v0.1.0.

You are welcome :-)