【问题标题】:How to Use postMessage on iFrame如何在 iFrame 上使用 postMessage
【发布时间】:2019-02-02 10:59:13
【问题描述】:

我有 2 个具有以下域的 nodeJS 应用程序:

  • 本地主机:8000
  • 本地主机:3000

在 localhost:3000 中,我有一个文本区域和一个提交按钮。

我想将 textarea 的内容(使用 postMessage)发布到 localhost:8000/(some_id),并在 localhost:8000 页面上显示内容。

然后,我想在 localhost:3000 页面中显示 localhost:8000/(some_id) 的 iFrame。

我在完成这项工作时遇到了很多麻烦。我必须使用 postMessage() 以这种方式完成它。

PS:我知道最好避免使用 iFrame,但是出于我的应用程序的目的,这是必须使用的。

【问题讨论】:

    标签: javascript node.js iframe csrf same-origin-policy


    【解决方案1】:

    无论您在一侧postMessage 发送什么,都会发送到另一侧的message 侦听器。

    // in the parent document
    iframeElement.contentWindow.postMessage('hi!');
    
    // in the iframe
    window.addEventListener('message', ({ data }) => {
      console.log('i got some data!', data); // i got some data! hi!
    });
    

    你也可以另辟蹊径,在 iframe 源中使用window.parent.postMessage(),在父文档中使用window.addEventListener('message', ...) 进行监听。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      相关资源
      最近更新 更多