代码之家  ›  专栏  ›  技术社区  ›  Kesavan R

window.parent.postmessage不使用iframe中的scr=“'data:text/html;charset=utf-8”

  •  0
  • Kesavan R  · 技术社区  · 6 年前

    我试图创建一个小编辑器,允许用户使用iframe编辑HTML。所以将html字符串作为数据传递到src:text/html。但是沟通并没有发生在父窗口中。

    帮助我做错事。

    索引文件

    <iframe id="creditMailBody"  class="iframe-main-content" src="{{creditMail.content}}"></iframe>

    在HTML字符串中

    <html>
    <head>
    </head>
    <body>
    <p id="editor" contentEditable="true"></p>
    </body>
    <script>
      document.getElementById("editor").addEventListener("input", function() {
        console.log("input event fired");
        window.parent.postMessage('iframe_message', '*')
      }, false);
     </script>
    </html>

    在控制器中

    window.addEventListener('iframe_message', function() {
      console.log('iframe message')
    }, true);
    1 回复  |  直到 6 年前
        1
  •  1
  •       6 年前

    Typo:

    事件被调用 message 不是 iframe_message :

    const frame_content = `<html>
    <head>
    </head>
    <body>
    <p id="editor" contentEditable="true">edit me</p>
    </body>
    <script>
      document.getElementById("editor").addEventListener("input", function() {
        console.log("input event fired");
        window.parent.postMessage('iframe_message', '*')
      }, false);
     <\/script>
    </html>`;
    frame.src = 'data:text/html,' + encodeURIComponent(frame_content);
    
    window.addEventListener("message", function() {
                          //  ^-- Here it is "message"
      console.log('iframe message')
    });
    <iframe id="frame"></iframe>