从iframe发出的消息上的window.addEventListener [英] window.addEventListener on a message emitted from an iframe
问题描述
我有两个html文件.第一个称为 post.html
,它在窗口上注册一个事件侦听器,并将消息发布到窗口:
I have two html files. The first is called post.html
and it registers an event listener on the window and posts a message to the window:
<html>
<head>
<script>
window.addEventListener("message", function(event) {
console.log("found event in post!", event)
});
window.postMessage({
'data': ["some data"]
},"*");
</script>
</head>
<body>
</body>
</html>
我还有另一个名为 listner.html
的html文件,该文件仅侦听来自窗口的消息并将 post.html
作为iframe加载:
I have a second html file called listner.html
that just listens for a message from the window and loads post.html
as an iframe:
<html>
<head>
<script>
window.addEventListener("message", function(event) {
console.log("event found in listen!", event)
});
</script>
</head>
<body>
<iframe src="post.html"></iframe>
</body>
</html>
如果我加载 listener.html
,则会收到一条日志,该日志指示 post.html
中的事件侦听器检测到在 post中发布到窗口的消息.html
,但我没有从 listener.html
获得任何日志.我的理解是,我应该能够通过 window
对象在两个文件之间进行通信,并且 listener.html
中的事件侦听器应该接收事件.知道为什么这行不通吗?
If I load listener.html
, I get the log indicating that the event listener in post.html
detected the message posted to the window in post.html
but I don't get any log from listener.html
. My understanding was that I should be able to communicate via the window
object between the two files and the event listener in listener.html
should receive the event. Any idea why this isn't working?
推荐答案
post.html
将消息发布到其自己的窗口中,而不是发布到包含 listener.html的窗口中代码>
post.html
is posting the message to its own window, and not to the window containing listener.html
window.parent.postMessage(...)
这篇关于从iframe发出的消息上的window.addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!