zoukankan      html  css  js  c++  java
  • (二)文档请求不同源之window.postMessage跨域

    一、基本原理

    HTML5为了解决跨域,引入了跨文档通信API(Cross-document messaging)。这个API为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。Internet Explorer 8+, chrome,Firefox , Opera和Safari 都支持这个功能。

    二、测试步骤

    1、创建a.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>window.postMessage解决跨域a.html</title>
    </head>
    <body>
    <script>
        window.onload = function() {
            var subwin = window.open('http://localhost:8081/b.html', 'title');
            //父窗口http://localhost:8080/a.html向子窗口http://localhost:8081/b.html发消息,调用postMessage方法。
            subwin.postMessage('我要给你发消息了!', 'http://localhost:8081');
        }
        window.addEventListener('message', function(e) {
          console.log('a.html接收到的消息:', e.data);
        });
    </script>
    </body>
    </html>

    发送消息,监听消息。

    2、创建b.html

    <script>
      var messageFunc = function (event) {  
          if(event.source != window.parent) {
            return;
          }
          var data = event.data,//消息  
          origin = event.origin,//消息来源地址  
          source = event.source;//源Window对象  
          if(origin == "http://localhost:8080"){  
            console.log('b.html接收到的消息:', data);
          }  
          source.postMessage('我已经接收到消息了!', origin);
        };  
        if (typeof window.addEventListener != 'undefined') {  
          window.addEventListener('message', messageFunc, false);  
        } else if (typeof window.attachEvent != 'undefined') {  
          window.attachEvent('message', messageFunc);  
        }
    </script>

    3、打开两个http服务器windowpostmessage跨域

    4、打开浏览器就可以看到结果:http://localhost:8080/a.html

  • 相关阅读:
    Codeforces Round #369 (Div. 2)
    Codeforces Round #361 (Div. 2)
    【转】.NET开发人员的瓶颈和职业发展
    【资料目录收藏】.NET开发必看资料53个 经典源码77个
    IT新人养成与蘑菇理论
    软件开发技术高手转向项目管理者要突破的误区
    关于程序猿的那些笑话
    工作流管理系统的应用
    工作流管理系统的标准和产品
    工作流系统的主要组成部分
  • 原文地址:https://www.cnblogs.com/camille666/p/cross_domain_window_postmessage.html
Copyright © 2011-2022 走看看