You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

父窗口打开的两个子窗口间通信问题求助

Fixing Cross-Window Communication Between A and B (Opened by Parent Window P)

Alright, let's break down why your attempts aren't working and walk through reliable fixes step by step.

First, let's spot the issues with your existing code:

  • Your first attempt: window.opener('A') is invalid syntax. window.opener is a reference to the parent window (P), not a function you can call with a window name. You can't use it directly to grab another child window like that.
  • Your second attempt: When you run window.open('','A') from window A, you're actually getting a reference to window A itself (since you're targeting the same window name). So you're sending a message to yourself, not to B—no wonder B never gets it.
  • Broadcast Channel issues: Chances are you either used mismatched channel names, didn't properly instantiate the channel in both windows, or (less likely) you're working in an older browser that doesn't support it (though modern browsers all do now).

Solution 1: Use the Parent Window as a Middleman

Since both A and B are opened by P, the parent window can hold references to both child windows, letting A and B access each other through P.

Step 1: Save child window references in Parent P

// In parent window P
const windowA = window.open('path', 'A');
const windowB = window.open('path', 'B');

// Attach references to the parent's window object so children can access them
window.childWindows = {
  A: windowA,
  B: windowB
};

Step 2: Send message from A to B via Parent P

// In window A
const messageData = { content: "Hey B, this is A!" };

// Wait for the parent to have the child references (add a timeout if needed for window loading)
if (window.opener && window.opener.childWindows) {
  const targetWindow = window.opener.childWindows.B;
  if (targetWindow) {
    // Replace "*" with your actual domain in production for security!
    targetWindow.postMessage(JSON.stringify(messageData), "*");
  }
}

Step 3: Listen for messages in B

// In window B
function receiveMessage(event) {
  // Critical: Verify the message comes from your trusted domain in production!
  // if (event.origin !== 'https://your-actual-domain.com') return;

  try {
    const message = JSON.parse(event.data);
    console.log("Message received from A:", message);
  } catch (err) {
    console.error("Failed to parse message:", err);
  }
}

window.addEventListener("message", receiveMessage, false);

Solution 2: Use Broadcast Channel API (No Parent Middleman Needed)

This is a cleaner, modern approach that lets windows communicate directly without relying on the parent.

Send message from A

// In window A
const channel = new BroadcastChannel('cross-window-chat');
const messageData = { content: "Hi B, direct message from A!" };

channel.postMessage(messageData); // No need to stringify—objects work natively!

// Clean up when window closes
window.addEventListener('beforeunload', () => {
  channel.close();
});

Listen for messages in B

// In window B
const channel = new BroadcastChannel('cross-window-chat');

channel.onmessage = (event) => {
  console.log("Direct message from A:", event.data);
};

// Clean up when window closes
window.addEventListener('beforeunload', () => {
  channel.close();
});

Note: Make sure both windows use the exact same channel name (here cross-window-chat)—that's probably why your earlier Broadcast attempt failed.


Critical Security Notes

  • Never use * for targetOrigin in production: Always specify your exact domain (e.g., 'https://your-app.com') to prevent sending data to untrusted sites.
  • Validate event.origin in message listeners: Ensure incoming messages only come from domains you trust to avoid malicious data.

内容的提问来源于stack exchange,提问作者sharath Hanumanthaiah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:02:42