PostMessage into iframe

Viewed 123

I have problems receiving a postmessage in an cross-domain embed in an iframe.

Domain 1 receives the 'handshake' send by the domain 2 application once it's loaded. This triggers it to send a confirmation (step 2). I can't seem to achieve a succesfull confirmation however, as step 3 never shows up in console. I've tried several versions of postMessage to domain 2, none of which seems to work. I'm probably not adressing the iframe in the right way.

In the simplest way, this is what I have on the embedding website:

<iframe id="idFrame" src="https://domain2.com" title=""></iframe>

<script> 
    window.onmessage = function(e){
        if (e.data == 'handshake') {
           document.getElementById('idFrame').contentWindow.postMessage('handshake confirmed', '*');
           console.log("Step 2: Handshake received and send confirmation"); 
        }
    };
</script>

This is the code on domain 2:

window.top.postMessage('handshake', '*'); // Step 1
window.onmessage = function(e){
    if (e.data == 'handshake confirmed') {
        console.log("Step 3: Handshake confirmation received"); 
    }
};

What's the mistake I'm overlooking?

Cheers!

0 Answers
Related