Of course you have to wait until the iframe is loaded before sending the message. Otherwise the games javascript-code would not be ready to catch it. E.g. you could add an event-listener to your iframe, so your code would look like:
let frame = document.getElementById('your-iframe-id'); frame.addEventListener("load", function () { frame.contentWindow.postMessage( /*JavaScript-variable containing the username as string*/, /*itch-io-domain-address*/); });