使用 Window.open 从父级打开的 2 个同级窗口之间的通信



我在 2 个窗口之间的通信中遇到问题,我有窗口 P 是父窗口。我使用 window.open('path',A( 打开新的 2 个新窗口(A, B(;和 window.open('path',B(。现在我需要在 A 和 B 之间进行通信。请帮助沟通黑白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 不起作用

您需要在所有窗口中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>

孩子.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>

最新更新