来自iframe的postMessage在新窗口中打开

时间:2016-10-16 08:41:07

标签: javascript postmessage

请我在下面的popop窗口打开一个小表格。

    <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
   $("#p1").toggleClass('classB');
    });
});
</script>
<style>
.classA{color:red;}
.classB{color:yellow;}
</style>


</head>
<body>

<h2 class="">Click the button to change the class</h2>

<p id="p1" class="classA">I will be changed when you pressed click me</p>


<button>Click me </button>

</body>
</html>

以上是父表单,并在服务器localhost:3000上运行。我打开了一个带有iframe的新窗口。我打算从弹出窗口或子窗口中postMessage并在父窗口中接收它。然后我修改了我的代码,添加了下面的onload。

<html>
<head>

</head>
<body>
    <div id="popUpDiv" style="display:none;"></div>
<script type="text/javascript"> 
    var popUpWindow;
    function popup(n) {
       popUpWindow = window.open("",n, "height=500,width=500");
    }
    function foo(obj){
    test1 = "http://localhost:3001"; 
    popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>');

    } 
</script>

 <a href="#" onclick="popup('popUpDiv');foo(this);">OnSale</a>
</body>
</html>

我的完整父页面现在如下所示。

window.onload = function() {.
    var messageEle = document.getElementById('message');
    console.log('its receiving message');
    function receiveMessage(e) {
        alert('received');
        console.log('the origin is ', e.origin);
        if (e.origin !== "http://localhost:3001"){
            return;
        }
        messageEle.innerHTML = "Message Received: " + e.data;
    }
    window.addEventListener('message', receiveMessage);
}

当我点击父级上的onSale链接时,它会从服务器3001打开我的孩子。但是,在子控制台上运行

<html> <head> </head> <body> <div id="popUpDiv" style="display:none;"></div> <script type="text/javascript"> var popUpWindow; function popup(n) { popUpWindow = window.open("",n, "height=500,width=500"); } function foo(obj){ test1 = "http://localhost:3001"; popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>'); } window.onload = function() { var messageEle = document.getElementById('message'); console.log('its receiving message'); function receiveMessage(e) { alert('received'); console.log('the origin is ', e.origin); if (e.origin !== "http://localhost:3001"){ return; } messageEle.innerHTML = "Message Received: " + e.data; } window.addEventListener('message', receiveMessage); } </script> <a href="#" onclick="popup('popUpDiv');foo(this);">OnSale</a> <div id="message"></div> </body> </html>

不会触发父级的receiveMessage事件。我确认我的活动已经附上。我尝试了一切可能但没有改变。请问我做错了什么?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

对不起,经过多次尝试,

parent.opener.postMessage('Hello', 'http://localhost:3000');

似乎工作正常。虽然需要研究原因。找到答案here