In this post :
https://www.wix.com/code/home/forum/questions-answers/postmessage-onmessage-no-longer-working
I noted the current erratic behaviour of onMessage when listening to a postMessage from HTML-component. I have used this for over half a year and always worked OK. But now I sometimes get a message from the component but mostly not.
I put the following on the Wix side as a test:
1) a html-component called html1
2) this code on the Wix side:
$w.onReady(function () {
$w("#html1").onMessage( (event) => {
console.log("in w:onMessage");
});
});
export function html1_message(event, $w) {
console.log("in w:onMessage thru props");
}
3) the following html in the component
<!doctype html>
<html>
<head>
</head>
<script type="text/javascript">
function sendLoadMessage () {
console.log("In sendLoadMessage of html");
window.parent.postMessage("LoadOk", "*");
console.log("loadok sent");
}
</script>
<body onload="sendLoadMessage ();">
</body>
</html>
The following happens:
1) preview mode no longer displays console.log´s at all
2) Publish Mode shows the two messages from the html-code, but not the console.log from the Wix site under the $w("#html1").onMessage( (event) => {
that is to say: 9 times out of 10 I don´t get it, 1 time I do. If I don´t console also displays "Slow network detected messages.
3) I noticed the html-component has a onMessage event in the Property Panel (never saw that before). When I put a console.log in there, it ALWAYS displays.
Question: why does the $w("#html1").onMessage( (event) => { no longer work reliably?
Hi Giri and Andreas,
I'll try to shortly explain a basic principle of iframes:
Loading an iframe is an asynchronous task, meaning you don't know the exact point that this will happen (and can't assume that page is ready when iframe is finished loading).
So if I'm trying to draw a timeline, here are two options:
1) page starts loading -> iframe starts loading -> page finished loading -> iframe finished loading
2) page starts loading -> iframe starts loading -> iframe finished loading -> page finished loading
Note: since iframes are inside a page, the page loading process fires up the iframe loading process so you would expect (and thus you can see) that most times, the page will finish loading before the iframe.
So, I'm guessing what you're trying to achieve should happen when both are ready.
I'd take the following approach:
On your global scope, set a variable:
let hasHappened = false;
Then, in $w('#html1').onMessage do:
$w("#html1").onMessage( (event) => { console.log("in w:onMessage"); hasHappend = true; });
in $w.onReady:
$w.onReady(function(){ if(!hasHappend) { $w("#html1").postMessage('StartNow'); } });
And inside your html component add a code that will deal with that using 'window.onmessage'.
Hope this makes sense and helps :)
Liran.