本篇文章给大家带来的内容是关于html5新机制:postMessage实现安全跨域通信(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
效果图
postmessage解析
-
HTML5提供了新型机制PostMessage实现安全的跨源通信. 语法
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow: 其他窗口的一个引用, 比如IFRAME的contentWindow属性, 执行,
window.open返回的窗口对象. message: 将要发送到其他窗口的数据. targetOrigin:
通过窗口的origin属性来指定哪些窗口能接收到消息事件, 其值可以是字符”*”(表示无限制)或者一个URL transfer:
是一串和message同时传递的Transferable对象. 这些对象的所有权将被转移给消息的接收方, 而发送一放将不再保有所有权. -
element.addEventListener(event,fn,useCaption ); 三个参数 event 事件 比如
click mouseenter mouseleave 回调函数 useCaption
用于描述是冒泡还是捕获。默认值是false,即冒泡传递。 当值为true,就是捕获传递。
实现方式
主界面 main.html
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<meta name=viewport content=width=device-width, initial-scale=1.0>
<meta http-equiv=X-UA-Compatible content=ie=edge>
<title>跨域数据访问</title>
<script type=text/javascript>
window.addEventListener('message',function(e){
console.log("e--->",e);
const data = e.data;
document.getElementById('main1').style.backgroundColor=e.data;
},false)
</script>
</head>
<body>
<p id=main1 style=width:200px;height:200px;margin:100px;border:solid 1px #000;>
我是主界面,等待接收iframe的传递
</p>
<p style=margin:100px;>
iframe
<iframe src=http://localhost:3000/iframe.html width=800px height=300px ></iframe>
</p>
</body>
</html>
iframe界面
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<meta name=viewport content=width=device-width, initial-scale=1.0>
<meta http-equiv=X-UA-Compatible content=ie=edge>
<title>Document</title>
<style type=text/css>
html,body{
height:100%;
margin:0px;
}
</style>
</head>
<body style=height:100%;>
<p id=frame style=height:200px; width:200px;background-color:rgb(204, 204, 0) onclick=changeColor()>
点击改变颜色
</p>
<script type=text/javascript>
function changeColor(){
var frame = document.getElementById('frame');
var color=frame.style.backgroundColor;
if(color=='rgb(204, 102, 0)'){
color='rgb(204, 204, 0)';
}else{
color='rgb(204,102,0)';
}
console.log("frame===>",frame);
console.log("color",color);
frame.style.backgroundColor=color;
window.parent.postMessage(color,'*');
}
</script>
</body>
</html>
相关推荐:
postMessage处理iframe 跨域问题_html/css_WEB-ITnose
H5中怎样使用postMessage实现两个网页间传递数据
以上就是html5新机制:postMessage实现安全跨域通信(代码)的详细内容,更多请关注双恒网络其它相关文章!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 精力有限,不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别
9.本站默认解压密码为:www.sudo1.com
本站提供的一切软件、教程和内容信息仅限用于学习和研究目的。
不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。
本站信息来自网络收集整理,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑或手机中彻底删除上述内容。
如果您喜欢该程序和内容,请支持正版,购买注册,得到更好的正版服务。
我们非常重视版权问题,如有侵权请邮件与我们联系处理。敬请谅解!
云资源网 » html5新机制:postMessage实现安全跨域通信(代码)
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 你们有qq群吗怎么加入?