0

I was wondering what is the difference between those two ways of listening a message.

Here is my assumptions:

window.onmesage = onMessage

This assign a function to the onmessage attribute of the window object. It will be executed every time I receive a message on my page. It allows to have only 1 listener for messages.

vs.

window.addEventListener("message", onMessage);

This adds an event listener to the message event. It will be executed every time I receive a message on my page. It allows to have multiple listener for messages.

Differences

If I call many times the first one, I will always have 1 function that is executed when receiving a message.

If I call X times the second one, I will have many listeners and when receiving a message, my onMessage function will be executed X times

Question

Are my assumptions correct?

Ganbin
  • 2,004
  • 2
  • 12
  • 19
  • if `onMessage` is always referring to the same function, then no, you'll have only one handler call per event. The difference is that if another script does `onmessage = myHandler` yours will be removed. – Kaiido Mar 17 '23 at 07:25

1 Answers1

1

Yes, your assumption is correct. Based on the answer of this question:

... addEventListener does not overwrite existing event handlers, whereas onmessage overrides any existing onmessage = fn event handlers ...

So only one function is executed if it includes as callback in window.onmessage while many functions can be executed using window.addEventListener

Jordy
  • 1,802
  • 2
  • 6
  • 25