window.postMessage实现跨域通信
来源:互联网 发布:高校一卡通网络 编辑:程序博客网 时间:2024/06/05 02:31
# window.postMessage概述
1.html5最常用的API之一,实现两个不同域窗口对象之间的数据通信。
2.在发送数据窗口执行:otherWindow.postMessage(msg,origin)
- otherWindow:表示接受数据的窗口的window对象,包括iframe的contentWindwohe和通过window.open打开的新窗口。
- msg表示要发送的数据,包扩字符串和对象(ie9以下不支持,可以利用字符串和json互换)。
- origin表示接收的域名。
3.在接受的窗口监听window的message事件,回掉函数参数接受一个事件对象event,包括的属性有:
- data:接受的数据
- origin:发送端的域
- source:发送端的DOMWindow对象
# 利用window.postMessage在框架之间发送数据
1.在父框架页面index.html发送obj对象给远程服务器的wozien.com/test/b.html,该页面是通过iframe加载的,如下
<!DOCTYPE html><html><head><title>window.postMessage</title></head><body><iframe id="proxy" src="http://wozien.com/test/b.html" onload = "postMsg()" style="display: none" ></iframe><script type="text/javascript">var obj = {msg: 'this is come from client message!'}function postMsg (){var iframe = document.getElementById('proxy');var win = iframe.contentWindow;win.postMessage(obj,'http://wozien.com');}</script></body></html>2.在远程页面b.html中监听message事件,先通过origin属性判断下数据来源的域是否可信任,加强安全措施。具体代码如下:
<!DOCTYPE html><html><head><title></title><script type="text/javascript">window.onmessage = function(e){if(e.origin !== 'http://localhost') return;console.log(e.origin+' '+e.data.msg);}</script></head><body><p>this is my server</p></body></html>3.在控制输出结果:
另外还可以在打开的新窗口中相互通信,具体查看相关链接演示。
0 0
- 使用window.postMessage实现跨域通信
- 使用window.postMessage实现跨域通信
- window.postMessage实现跨域通信
- 利用HTML5的window.postMessage实现跨域通信
- 利用HTML5的window.postMessage实现跨域通信
- window.postMessage跨页面通信
- 用postMessage实现跨域通信
- HTML5之window.postMessage实现跨域传递消息
- window.name 结合postMessage api 实现跨域
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
- HTML5之postMessage和setEventListener实现<iframe>跨域通信
- postMessage()实现跨域
- HTML5 postMessage和跨域通信
- iframe跨域通信--html5.postmessage
- html5跨域通信之postMessage
- 使用html5 postMessage和window.name实现多浏览器跨域
- MFC ActiveX的创建和调用
- CDN的四大关键技术
- 苹果手机下不是a标签却有了a标签的样式的解决方案
- mysql优化,不用怕面试题了
- 无线轮播
- window.postMessage实现跨域通信
- Listview条目多样化
- html的三大元素
- 前向声明
- Request的getParameter和getAttribute方法的区别
- Java基础学习之InputStream的read()方法陷阱
- 远程获取图片二进制流及保存到本地
- windows下安装php5.5的redis扩展
- Vijos P1303 导弹拦截(动态规划,LIS)