如何从 postMessage() 访问数据?

How to access data from postMessage()?

我看过关于这个主题的各种问答,但我无法通过。 read/access 我要发送的对象有问题。它似乎是未定义的。 我有一个父 window 和一个通过 iframe 加载的页面。出于测试目的,我在同一个应用程序中使用了 2 个不同的页面。

const iframElem = document.getElementById('iframeID');
(iframElem as HTMLObjectElement).contentWindow?.postMessage({myData: 'TEST'}, 'http://localhost:3001/home');

<iframe
   id="iframeID"
   src="http://localhost:3001/account"
   title="title"
></iframe>

在通过 iframe 调用的页面中,我有这个:

if (window.addEventListener) {
  window.addEventListener('message', handleMessage, false);
}
function handleMessage(e: MessageEven) {
  console.log('DATA, payload', e.data.myData);
}

有了这个,我得到了 .myData - undefined。当我只记录数据时,我得到下一个:

instanceId: 1
maxAge: 50
nextActionId: 62
source: "@devtools-page"
type: "ACTION"
action: "{..something about chunks and javascript...}"
payload: "{....long one - appears to be redux data from the app...}"
__proto__: Object

我也用了 .postMessage(JSON.stringify(...)) 和 JSON.parse(e.data),但没有用。

经过几天的努力和思考为什么它不起作用以及我在这里缺少什么,我找到了解决方案。首先帮助我的是。使用 setTimeout 和延迟,我首先验证消息对象实际上是从父 window 发送到 iframe。

我在本地有 2 个应用 运行:前端 1 (http://localhost:3001) 和前端 2 (http://localhost:3003)

最终解决方案将包括在我们使用 postMessage() 之前确认 iframe 已加载。当加载 iframe 时,.postMessage() 方法用于将数据从父 window 转发到 iframe。所以父 window 中的代码如下所示:

window.addEventListener('message', (event: MessageEvent) => {
if (event.origin === 'http://localhost:3003') {
  if (event.data === 'iframe loaded!') {
      const iframeElem = window.document.getElementById('iframe-id') as HTMLIFrameElement;
      iframeElem.contentWindow?.postMessage({token: tokenObj.token, platform: tokenObj.platform}, 'http://localhost:3003');
  }
}});

return (
      <iframe
        id="iframe-id"
        src={src}
        title={title}
      ></iframe>
  );

并且在 iframe 中我们检查 window 和父 window 实际上是不同的,如果它们是不同的,我们使用在父 [=27 中处理的 postMessage('iframe loaded!') =].当 postMessage() 从父 window 到 iframe 完成时,我们有 'message' 事件的事件侦听器。

if (window !== window.parent) {    
    window.parent.postMessage('iframe loaded!', 'http://localhost:3001');
  }

  window.addEventListener('message', (event: MessageEvent) => {;
    if (event.origin === 'http://localhost:3001') {
      // do what you need...
    }
  });

前端环境为React和typescript。此外,这仅在 google chrome 浏览器中进行了测试。

window.location.pathname,d=_CW_BUILD_INFO.buildNumber,e=_CW_BUILD_INFO.masteringNumber;window.parent.postMessage(JSON.stringify({appName:c,buildNumber:d,masteringNumber: e,args:[a,b],isCloudOSMessage:!0,methodName:"recordApplicationMessage"}),"*")}}函数 buildMessageFromErrorEvent(a){var