• 通过 Channel Messaging API的「MessageChannel」,实现iframe与主页面的双通讯


    demo地址:https://mdn.github.io/dom-examples/channel-messaging-basic/

    原文来自:https://developer.mozilla.org/zh-CN/docs/Web/API/MessageChannel

    index.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width">
        <title>Channel messaging demo</title>
        <link rel="stylesheet" href="">
        <!--[if lt IE 9]>
          <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
      </head>
      <body>
        <h1>Channel messaging demo</h1>
        <p class="output">My body</p>
        <iframe src="./page.html" width='480' height='320'></iframe>
      </body>
      <script>
        var channel = new MessageChannel();
        var output = document.querySelector('.output');
        var iframe = document.querySelector('iframe');
    
        // Wait for the iframe to load
        iframe.addEventListener("load", onLoad);
        
        function onLoad() {
          // Listen for messages on port1
          channel.port1.onmessage = onMessage;
          // Transfer port2 to the iframe
          iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
        }
    
        // Handle messages received on port1
        function onMessage(e) {
          output.innerHTML = e.data;
        }
      </script>
    </html>

    page.html (iframe嵌入的页面)

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width">
        <title>My page title</title>
        <link rel="stylesheet" href="">
        <!--[if lt IE 9]>
          <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
      </head>
      <body>
        <p class="output">iFrame body</p>
      </body>
      <script>
      var output = document.querySelector('.output');
    
      window.addEventListener('message', onMessage);
      
      function onMessage(e) {
          output.innerHTML = e.data;
        // Use the transfered port to post a message back to the main frame
          e.ports[0].postMessage('Message back from the IFrame');
      }
      </script>
    </html>
  • 相关阅读:
    深入理解hadoop之MapReduce
    centos关机与重启命令
    hadoop学习笔记(1)
    配置ssh免密码登录设置后还是提示需要输入密码
    js获得URL中的参数
    SQLite介绍
    sql记录
    sql游标使用
    sql触发器
    sql函数
  • 原文地址:https://www.cnblogs.com/liujinyu/p/13927105.html
Copyright © 2020-2023  润新知