[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[备忘]iframe跨域执行Js之postMessage

上一篇:[备忘]FastJson解析下划线字段问题 _id
下一篇:[备忘]cas单点退出时,清掉shiro的session

添加日期:2017/7/25 1:17:08 快速返回   返回列表 阅读1940次
HTML5新增方法,现在浏览器及IE8+支持,简单易用高大上。

.postMessage(message, targetOrigin)

参数说明
message: 是要发送的消息,类型为 String、Object (IE8、9 不支持) 
targetOrigin: 是限定消息接收范围,不限制请使用 '*'

'message', function(e)回调函数第一个参数接收 Event 对象,有三个常用属性:
data: 消息
origin: 消息来源地址
source: 源 DOMWindow 对象
-------------------------
一个简单的父页面foo.com/a.html 和子页面 bar.com/b.html建立通信


<!-- foo.com/a.html -->
<iframe id="ifr" src="http://bar.com/b.html"></iframe>
<script>
window.onload = function () {
    var ifr = document.querySelector('#ifr');
    ifr.contentWindow.postMessage({a: 1}, '*');
}
window.addEventListener('message', function(e) {
    console.log('bar say: '+e.data);
}, false);
</script>




<!-- bar.com/b.html -->
window.addEventListener('message', function(e){
    console.log('foo say: ' + e.data.a);
    e.source.postMessage('get', '*');
}, false)

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved