【问题标题】:Can't use postMessage in react components无法在反应组件中使用 postMessage
【发布时间】:2020-11-29 07:10:16
【问题描述】:

我试图打开一个弹出窗口并从反应组件传递一条消息,窗口打开(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').

【问题讨论】:

    标签: javascript reactjs cross-domain postmessage


    【解决方案1】:

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

    Broadcast Channel

    【讨论】:

    猜你喜欢
    • 2018-11-26
    • 2017-05-06
    • 2020-08-27
    • 2020-05-19
    • 2019-02-21
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多