使用postMessage API进行通信
示例代码:在窗口1中发送消息,窗口2接收并响应消息
在窗口1中:
const targetOrigin = 'http://localhost:8080'; // 目标窗口的源
const targetWindow = window.open(targetOrigin); // 打开目标窗口
const message = 'Hello from window 1!'; // 发送的消息
targetWindow.postMessage(message, targetOrigin); // 发送消息到目标窗口
在窗口2中:
window.addEventListener('message', function(event) {
if (event.origin !== 'http://localhost:8080') return; // 来源不匹配,忽略
if (event.data === 'Hello from window 1!') { // 接收到正确的消息
console.log('Received message:', event.data);
const responseMessage = 'Hello from window 2!'; // 响应消息
event.source.postMessage(responseMessage, event.origin); // 发送响应消息
}
});