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