跨站点 postMessage 未被 addEventListener 接收
cross site postMessage isn't picked up by addEventListener
我的网页中嵌入了 itch.io 的 iframe。 iframe 通过 postMessage 向我发送消息:
//This gets send from a Unity WebGL game
SendMessageToPage: function (text) {
var convertedText = Pointer_stringify(text);
// Pass message to the page
window.parent.postMessage(convertedText, "*");
}
父网页(我嵌入了 iframe 的网站,所以它应该是父网页,对吧?)应该用事件监听器来获取它:
<script>
alert("Hello") //<-This one fires
window.addEventListener('message', function(event){
alert("Hello from);
if (event.origin != 'https://itch.io') {
alert("Unknown Source");
return;
}
alert("received: " + event.data)
});
</script>
此外,我还有一个 div 元素来接收消息
<script>
document.getElementById("WriteOut").addEventListener('message', function(e){
document.getElementById("WriteOut").innerHTML="Got Something";
});
</script>
我看到控制台日志中出现了 itch 发送的消息,所以我有点怀疑我没有正确配置事件监听器。该消息也仅在网站加载后很长时间才出现(页面打开后 atm ~15 秒),因此未加载侦听器应该不是问题。
有谁知道发生了什么事吗?据我所知,我传递了正确的论点。
我找到了修复/真正的问题:
由于游戏不是直接在 iframe 中 运行,因此 window.parent 没有通过侦听器处理 window,而是在两者之间处理一些 window。将其更改为
//This gets send from a Unity WebGL game
SendMessageToPage: function (text) {
var convertedText = Pointer_stringify(text);
// Pass message to the page
window.top.postMessage(convertedText, "*");
}
成功了。
我的网页中嵌入了 itch.io 的 iframe。 iframe 通过 postMessage 向我发送消息:
//This gets send from a Unity WebGL game
SendMessageToPage: function (text) {
var convertedText = Pointer_stringify(text);
// Pass message to the page
window.parent.postMessage(convertedText, "*");
}
父网页(我嵌入了 iframe 的网站,所以它应该是父网页,对吧?)应该用事件监听器来获取它:
<script>
alert("Hello") //<-This one fires
window.addEventListener('message', function(event){
alert("Hello from);
if (event.origin != 'https://itch.io') {
alert("Unknown Source");
return;
}
alert("received: " + event.data)
});
</script>
此外,我还有一个 div 元素来接收消息
<script>
document.getElementById("WriteOut").addEventListener('message', function(e){
document.getElementById("WriteOut").innerHTML="Got Something";
});
</script>
我看到控制台日志中出现了 itch 发送的消息,所以我有点怀疑我没有正确配置事件监听器。该消息也仅在网站加载后很长时间才出现(页面打开后 atm ~15 秒),因此未加载侦听器应该不是问题。
有谁知道发生了什么事吗?据我所知,我传递了正确的论点。
我找到了修复/真正的问题: 由于游戏不是直接在 iframe 中 运行,因此 window.parent 没有通过侦听器处理 window,而是在两者之间处理一些 window。将其更改为
//This gets send from a Unity WebGL game
SendMessageToPage: function (text) {
var convertedText = Pointer_stringify(text);
// Pass message to the page
window.top.postMessage(convertedText, "*");
}
成功了。