来自在新 window 中打开的 iframe 的 postMessage

postMessage from an iframe opened in in new window

请给我一个小表格,我可以在 popop window 上打开它,如下所示。

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

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

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);
}

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

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

当我在父级上单击 onSale link 时,它从服务器 3001 打开了我的子级。但是,运行 在子级控制台上

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

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

抱歉,经过多次尝试,

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

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