一、基本原理

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

最新文章

  1. python学习之路 第三天
  2. 国内npm镜像源推荐及使用
  3. FTP 的搭建过程和遇到的问题
  4. Apache Thrift 服务开发框架学习记录
  5. 介绍linux下vi命令的使用
  6. 炫酷JQUERY自定义对话框插件JDIALOG_JDIALOG弹出对话框和确认对话框插件
  7. Marshal.SecureStringToBSTR
  8. CodeForces 489B BerSU Ball (贪心)
  9. CF#190DIV.1
  10. Redis和Memcache的区别分析 [转]
  11. logback logback.xml 常用配置详解
  12. Mybatis JPA 代码构建
  13. shell中,我们可以通过简单的一个判断来判断命令是否存在
  14. 微信开发中网页授权access_token与基础支持的access_token异同 【转载、收藏】
  15. HDU 1026(迷宫 BFS+打印)
  16. GBT 33200-2016 社会治安综合治理 综治中心建设与管理规范 GBT 31000-2015 社会治安综合治理基础数据规范
  17. securecrt配置经验总结(home.key和颜色)
  18. 【译】第17节---数据注解-Column
  19. 有关Set集合的一个小问题
  20. idea不识别yml配置文件,怎么办?

热门文章

  1. Count on a tree SPOJ - COT (主席树,LCA)
  2. 解决Navicat远程连接MySQL出现 10060 unknow error
  3. IDEA或Webstorm设置Terminal终端字体大小
  4. java-查看java源码
  5. Qt: 非阻塞时间延迟;
  6. SSH HTTP代理
  7. 调用腾讯、百度翻译API,实现游戏机翻通用程序
  8. Linux之搭建远程数据库[Ubuntu:全过程]
  9. 阿里的fastJson.jar jsonArray 和 list 互转
  10. 7系列FPGA的时钟资源——UG472