(二)文档请求不同源之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

转载于:https://www.cnblogs.com/camille666/p/cross_domain_window_postmessage.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值