Game in iframe not capturing postMessage data after parent reload

Not favoritedFavorited Favorited 0 favourites
  • 2 posts
From the Asset Store
HTML5 Game Bundle (7 Games) – Created with Construct 3
  • Hi everyone,

    I'm embedding my Construct 3 game in an iframe inside a parent webpage. I'm passing userId and orgId from the parent using postMessage, and I’m capturing it in the game using an addEventListener inside main.js (in the scripts folder of the exported project).

    Everything works fine the first time—the game receives the data and stores it.

    However, when I reload the parent page, the game doesn't capture the postMessage data again, even though I'm still sending it from the parent. It seems like the event listener in main.js isn't picking it up after a reload.

    Here's what I've done:

    In main.js, I've added:

    	window.addEventListener("message", function (event) {
     // basic check
     if (event.data.userId && event.data.orgId) {
     console.log("Received:", event.data);
     // You can then store it or send to Construct
     window.userId = event.data.userId;
     window.orgId = event.data.orgId;
     }
    });
    

    ]

    The message is being sent from the parent like:

    js

    Copy

    Edit

    iframe.contentWindow.postMessage({ userId: "123", orgId: "456" }, "*");

    I'm sending c3ready from game to parent saying that game is ready . Parent is sending data only after game sends signal whether is ready

    My questions:

    Does the Construct game take time to load before it’s ready to receive messages?

    Do I need to reattach the listener or trigger something from the parent after reload?

    Is there a better way to pass data every time the parent reloads?

    Any help would be appreciated. Thank you!

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Does the Construct game take time to load before it’s ready to receive messages?

    It depends when you add the event listener in your code.

    You might have a race between loading the parent page and loading the iframe. If one sends a message before the other is listening, it won't work (and will fail intermittently depending on how long loading works).

    There are various strategies to deal with this - one for example might be to make sure the parent page is listening before the iframe is loaded, and then post a ready message from the iframe to the parent once the iframe is listening, after which the parent can safely post to the iframe. Another is just to post messages to the iframe regularly on a timer and send an acknowledgement back from the iframe once received, at which point the parent can stop posting.

Jump to:
Active Users
There are 0 visitors browsing this topic (0 users and 0 guests)