Behavioral difference for HTML iFrame component between Preview and Published pages

Hi. I have a page with an HTML iFrame component and Page Code. The Page Code will call a Web Module that fetch data from third party using their API. The data fetched will then be sent to the HTML iFrame component by the PageCode using postMessage. The HTML iFrame will get the data using :
window.onmessage = (event) => {
if (event.data) {
var receivedData = event.data;
alert(receivedData);
….
and the data is displayed (inside the html code that formats the data into an html table with labels) accordingly.

Issue :
When in Preview mode, everything worked fine (i.e. the alert statement in the code above showed the recieved data, and data fetched is displayed in the HTML iFrame). However, after I published the code and then go to “View Site”, there is NO alert dialogue popping up and the data is not displayed on the page. Only the html code (i.e.t he html table border and labels) are displayed on the page. I have verified using console.log in the Page Code that data fetch is successful and displayed on console.log. However, when I do “View Site”, there is no alert box with receivedData.

Obviously there is a difference in behaviour between the “Preview” and “Published” mode as described above. At first I thought it was a timing issue where the HTML code in the iFrame is rendered first without the data. So I put in a delay (which is long enough as I see the data showing in the console.log long before the end of the delay) to wait for the data before displaying. It doesn’t work.

Any ideas how to fix that?

Hi,
My guess that it happens because asynchronous between the html component and the main page component.
Check out this thread for more information:

Good luck!
Roi.

Hi, Roi. Thank you for the pointers. I modifiied my code using the solution suggested in the thread you posted and it worked.

Thanks again.