使用 Window.open 从父级打开的 2 个兄弟 windows 之间的通信

Comunication between 2 sibling windows opened from parent using Window.open

我在 2 Window 之间的通信中遇到问题我有 window P,它是父 window。我打开 new 2 new window(A, B) 使用 window.open('path',A);和 window.open('path',B)。现在需要A和B之间进行通信,请大家帮忙通信B/wA和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 没用

您总共需要 message 个侦听器 windows。所有打开的windows(这里是A和B)都会postMessage()window.opener(这里是P)。然后,P 会将每条收到的消息转发给所有 windows 打开的消息,除了该消息的来源。

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