【问题标题】:Comunication between 2 sibling windows opened from parent using Window.open使用 Window.open 从父级打开的 2 个同级窗口之间的通信
【发布时间】:2020-05-24 15:31:28
【问题描述】:

我在 2 个窗口之间的通信中遇到问题我有窗口 P,它是父窗口。我使用 window.open('path',A); 打开新的 2 个新窗口(A,B);和 window.open('path',B)。现在我需要在 A 和 B 之间进行通信。请帮助 B/w A 和 B 进行通信。

我试过了,还是不行

// In A component
window.opener('A').postMessage(JSON.stringify(messageData), "*"); 

//In B component
window.addEventListener("message", this.receiveMessage.bind(this), false);

我也试过了,还是不行

// IN A component
window.open('','A').postMessage(JSON.stringify(messageData), "*");

// IN B component
window.addEventListener("message", this.receiveMessage.bind(this), false);

另外一个我用的 BroadCast 没用

【问题讨论】:

  • 这个问题的状态如何?
  • 我通过 postMessage 解决了这个问题

标签: javascript angular cross-browser broadcastreceiver window.open


【解决方案1】:

您需要在所有窗口中都有message 侦听器。所有打开的窗口(此处为 A 和 B)都将转到 postMessage() 到 window.opener(此处为 P)。然后,P 会将收到的每条消息转发到所有打开的窗口,但该消息的源(来源)除外。

父.html

<html>
    <head>
        <script>
            //REM: Contains all opened windows
            const openedWindows = [];

            window.onload = function(){
                //REM: Listener to receive postMessage()
                window.addEventListener('message', function(event){
                    //REM: Just writes the output
                    document.body.appendChild(document.createTextNode(event.data));

                    //REM: Forwards the message to all opened windows but the source
                    for(var i=0, j=openedWindows.length; i<j; i++){
                        if(openedWindows[i] !== event.source){
                            openedWindows[i].postMessage(event.data, '*')
                        }
                    }
                }, false);

                //REM: Opens child window A
                openedWindows.push(window.open('Child.html', 'A'));

                //REM: Opens child window B
                openedWindows.push(window.open('Child.html', 'B'))
            }
        </script>
    </head>

    <body>
    </body>
</html>

Child.html

<html>
    <head>
        <script>
            window.onload = function(){
                //REM: Listener to receive postMessage()
                window.addEventListener('message', function(event){
                    //REM: Just writes the output
                    document.body.appendChild(document.createTextNode(event.data));
                }, false);

                //REM: Populating message for demo purpose
                window.setInterval(function(){
                    window.opener.postMessage('Hi! Message from window "' + window.name + '"', '*')
                }, 1000)
            }
        </script>
    </head>

    <body>
    </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多