首页 > 解决方案 > 无法在反应组件中使用 postMessage

问题描述

我正在尝试打开一个弹出窗口并从反应组件传递一条消息,窗口打开(http://localhost:3001)但未显示消息。下面是打开 popup 和 postMessage 到弹出窗口的代码:

  React.useEffect(() => {
    document.addEventListener("message", function(event) {
      console.log('event data', event.data, event.source);
    })
  }, []);

  const onAdd = () => {
    const popup = window.open('http://localhost:3001/auth', 'authWindow','height=500,width=500');
    popup.postMessage('data', 'http://localhost:3001');
  }

在那个弹出窗口(http://localhost:3001/)打开我想向我的父窗口(http://localhost:3000/)传递一条消息,这是将消息传递给父级的代码:

  const receiveMessage = (e) => {
    console.log("message event",  e.data);

    e.source.postMessage("message: asasdas", 'http://localhost:3000')
    // if (event.origin !== "http://localhost:3000")
    //   return;
  }

  React.useEffect(() => {
    window.addEventListener("message", receiveMessage);
  }, [])

但这也给出了一个错误: Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3000') does not match the recipient window's origin ('http://localhost:3001').

标签: javascriptreactjscross-domainpostmessage

解决方案


使用BroadcastChannel API. 我在我的项目中使用它并发现它更可靠。我没有看到你遇到的问题。

广播频道


推荐阅读