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>
  • 相关阅读:
    经典回溯问题--八皇后dfs递归回溯求解【DFS】
    CSP认证考试(第九次)第一题
    C++字符串和数字格式转化(使用sprintf()和sscanf()函数)
    2016蓝桥杯C++A组第六题 寒假作业【暴力搜索】
    先序非递归建立二叉树
    sqlsrv数据库复杂语句1
    tp5域名配置
    JavaScript使用 value 属性
    数据库随机查询6条数据
    文件目录问题
  • 原文地址:https://www.cnblogs.com/liujinyu/p/13927105.html
Copyright © 2011-2022 走看看