我正在尝试通过发送包含字符串化对象的消息来使两个 React 应用程序进行通信。
父级(http://localhost:3000)通过 postMessage 发送消息,如下所示:
let iframe = document.querySelector("iframe")
useEffect(() => {
if (!!localStorageObject && !!iframe) {
iframe?.contentWindow?.postMessage(localStorageObject, "http://localhost:3001")
}
}, [localStorageObject, iframe])
// ...file and start of return
<iframe
style={{minHeight: window.outerHeight, width: '100%', border: "none"}}
referrerPolicy="strict-origin-when-cross-origin"
src={myUrlWithParams}
title="App"
allow="clipboard-write"
id={"iframe"}
/>
iFrame (http://localhost:3001) 没有收到消息,至少没有立即收到消息(我必须等待反应软刷新才能显示日志)。
首先抛出的错误是:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3001') does not match the recipient window's origin ('http://localhost:3000'). Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是因为当您调用此
postMessage()方法时,您的 iframe 文档尚未加载,因此您收到的contentWindow是原始about:blank文档之一,而不是您期望的文档。有人可能会说,这里的错误消息有点令人困惑,并且您的开发工具可能会更好(也?)报告该位置的来源是
about:blank(即使它是已检查的全局文档的origin对于postMessage())。但无论如何,要解决该问题,请等待
<iframe>的load事件。 (很抱歉,我不是一个reactJS忍者,所以我会让你找到最好的方法来做到这一点)。这是应用了解决方案的普通重现设置:https://jsfiddle.net/382pz5er/ (外包是因为 StackSnippet 的 null 起源帧在这里是一个坏例子)。