解决从父窗口向 iframe 使用 postMessage 时的原始错误(在 DOMWindow 上执行 'postMessage' 失败)
P粉178894235
P粉178894235 2024-03-28 14:15:43
0
1
419

我正在尝试通过发送包含字符串化对象的消息来使两个 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').

P粉178894235
P粉178894235

全部回复(1)
P粉670838735

这是因为当您调用此 postMessage() 方法时,您的 iframe 文档尚未加载,因此您收到的 contentWindow 是原始 about:blank 文档之一,而不是您期望的文档。

有人可能会说,这里的错误消息有点令人困惑,并且您的开发工具可能会更好(也?)报告该位置的来源是 about:blank (即使它是已检查的全局文档的 origin对于 postMessage())。

但无论如何,要解决该问题,请等待 <iframe>load 事件。 (很抱歉,我不是一个reactJS忍者,所以我会让你找到最好的方法来做到这一点)。

这是应用了解决方案的普通重现设置:https://jsfiddle.net/382pz5er/ (外包是因为 StackSnippet 的 null 起源帧在这里是一个坏例子)。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!