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