Sending data to html component in onReady function

I am trying to use the postMessage/onMessage architecture in the onReady function to send some data but it is not working.

Does onReady not guarantee that my component is listening for messages?

Here is my code:

Component CODE:

<!doctype html>
<html>
<head>
<script type="text/javascript">
function init () {
 // when a message is received from the page code
  window.parent.postMessage('READY', '*');
  window.onmessage = (event) => {
    if (event.data) {
      console.log("HTML Code Element received a message!");
    }
  }
}
</script>
</head>
<body onload="init()" style="background-color:lightgray;"></body>
</html>

Page CODE:

 import {fetch} from 'wix-fetch'; 
 import {getLatestEpisode, getCurrentTemp} from 'backend/spreakerModule'; 
 let htmlDone = false;
 $w.onReady(function () {
   $w("#mostRecentEpisode").onMessage(event => {
     if (event.data === "READY" && htmlDone === false) {
       console.log(event.data);
       $w("#mostRecentEpisode").postMessage("Send");
       getLatestEpisode().then(episode => {
         console.log(episode);
         $w("#mostRecentEpisode").postMessage("Send");
       })
       htmlDone = true;
      }
    })
 });

I suggest you modify the tag in your HTML code to make it look like this

<body onload="window.parent.postMessage('READY', '*');">

So when the HTML code has been fully loaded then it will send the Wix Code a message of READY.

And then in your Wix Code part of things check the below

let htmlDone = false;
    $w.onReady(function () {
        $w("#mostRecentEpisode").onMessage(event => {
            if (event.data === "READY" && htmlDone === false) {
                console.log(event.data);
                $w("#mostRecentEpisode").postMessage("Send");
                htmlDone = true;
            }
        })
    });

This works for me

Thanks that works for sending the message to the page code but it is not clear whether the HTML actually receives the acknowledgement message from the page code. I edited the code in the original post to reflect your changes. Using that code, I do not get any logs to the console from the HTML’s window.onmessage statement even though the page code sends a message.