首页 > Windows开发 > 详细

window.postMessage解决跨域

时间:2017-07-18 13:19:09      阅读:379      评论:0      收藏:0      [点我收藏+]

一、基本原理

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服务器技术分享

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

window.postMessage解决跨域

原文:http://www.cnblogs.com/camille666/p/cross_domain_window_postmessage.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!