I have an iframe from itch.io embedded in my webpage. The iframe sends me a message via 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, "*");
}
The parent webpage (the website I have embedded the iframe in, so it should be the parent, right?) is supposed to pick it up with an Event Listener:
<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>
Additionally I have a div element to receive the message
<script>
document.getElementById("WriteOut").addEventListener('message', function(e){
document.getElementById("WriteOut").innerHTML="Got Something";
});
</script>
I can see that the message sent from itch appears in the console log, so I kinda suspect that I didn't configure the event listeners correctly. The message also only comes in long after the website has loaded (atm ~15sec after page opening), so it shouldn't be a problem with the listener not being loaded in.
Does anyone have an idea what is going on? As far as I can tell I pass the right arguments.
I found a fix / the real problem: As the game was not running directly in iframe, window.parent did not address the window with the listener, but some window in between. changing it to
//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, "*");
}
worked.