Fane
Fane

Reputation: 2074

postMessage not being received from iframe

Here is the code in the iframe with src="example.com"

<script>

    var domain = "http://example2.com";

    function redirectRequest(){

        console.log("window.opener",window.opener); // NULL
        console.log("window.top",window.top); // script_name
        console.log("window.parent",window.parent); // script_name

        opener.postMessage("redirect", domain); //fails because null
       //top and parent also do not work BUT do not display errors
    }

</script>

and here is the code running in example2.com which contains the postMessage receiver (and also contains the iframe):

function message_listener(event) { //nothing is ever received...

   console.log("event received",event); 

   var data = event.data;

   console.log("data received",data);

}


if (window.addEventListener) {
   window.addEventListener("message", message_listener);
} else {
   // IE8
   window.attachEvent("onmessage", message_listener);
}

Any idea what might be off? Thank you very much...

Upvotes: 2

Views: 4731

Answers (2)

TitanFighter
TitanFighter

Reputation: 5074

In my case for some reason this helped:

// Inside iframe
window.parent.socket.postMessage('msg example', '*');

Upvotes: 0

antoniOS
antoniOS

Reputation: 419

For iframe you need to replace opener to parent. replace this:

opener.postMessage("redirect", domain);

to this:

window.parent.postMessage("redirect", domain);

Upvotes: 2

Related Questions