zoukankan      html  css  js  c++  java
  • 通过 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>
  • 相关阅读:
    【转】Android 6.0 Marsmallow BLE : Connection Parameters
    过滤掉字符串中重复的字符
    从第一个汉字开始分割字符串
    根据年月生成日历函数
    计算两个日期之间的工作日
    根据日期返回星座
    检查给定串是否存在于由区间及点集的结合内
    将整型数字转换为大写汉字
    向左填充指定字符串
    人民币小写金额转大写
  • 原文地址:https://www.cnblogs.com/liujinyu/p/13927105.html
Copyright © 2011-2022 走看看