Связь между двумя братьями и сестрами windows, открытыми от родителя с помощью Window.open - PullRequest
0 голосов
/ 09 февраля 2020

Я сталкиваюсь с проблемами в связи между окном 2 У меня есть окно P, которое является родительским окном. Я открываю новые 2 новых окна (A, B), используя window.open ('path', A); и window.open ('путь', 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 не работал

1 Ответ

0 голосов
/ 09 февраля 2020

Вам понадобится 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>
...