javascript window.addEventListener('message') 是否覆盖其他侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22204902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does window.addEventListener('message') overwrite other listeners?
提问by Chris Wilson
I've got some code that communicates with an iframe using .postMessage()
, meaning it needs to add a listener on message
to receive communication from the iframe. I'm using the usual code for that:
我有一些代码使用 与 iframe 进行通信.postMessage()
,这意味着它需要添加一个侦听器message
来接收来自 iframe 的通信。我正在使用通常的代码:
window.addEventListener('message', processMessage, false);
This code runs on a client's page that has a bunch of other stuff on it: Analytics, social buttons, etc. etc. I noticed when I added a console.log
to the processMessage
function to debug communication from the iframe, it was picking up a lot of other traffic from third-party plugins that also use .postMessage
.
这个代码在客户端的网页上运行的是拥有一堆其他的东西就可以了:分析,社交按钮,等等,等等,我注意到,当我加入了console.log
该processMessage
功能从IFRAME调试通信,这是捡了很多其他来自第三方插件的流量也使用.postMessage
.
It's not a problem to ignore them, since I'm looking for very specific messages from the iframe, but I want to make sure I'm not overwriting whatever listener was supposed to pick up those messages from the FB script and so forth. I've had issues before with multiple window.onresize
events overwriting one another. Is that an issue with the event listener for messages?
忽略它们不是问题,因为我正在寻找来自 iframe 的非常具体的消息,但我想确保我没有覆盖任何应该从 FB 脚本中获取这些消息的侦听器等等。我之前遇到过多个window.onresize
事件相互覆盖的问题。这是消息的事件侦听器的问题吗?
回答by Will P.
addEventListener
does not overwrite existing event listeners, it simply adds a new one as the method name implies. Existing listeners must be removed using the removeEventListener
method.
addEventListener
不会覆盖现有的事件侦听器,它只是像方法名称所暗示的那样添加一个新的事件侦听器。必须使用该removeEventListener
方法删除现有侦听器。