postMessage not being received from iframe

旧巷老猫 提交于 2019-12-13 04:49:59

问题


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...


回答1:


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

opener.postMessage("redirect", domain);

to this:

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


来源:https://stackoverflow.com/questions/33630495/postmessage-not-being-received-from-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!