沉沙
2018-06-05
来源 :
阅读 1456
评论 0
摘要:postMessage()方法可以使不同源的脚本采用异步方式进行数据传递,希望阅读本篇文章以后大家有所收获,帮助大家对HTML5的理解更加深入。
postMessage()方法可以使不同源的脚本采用异步方式进行数据传递。
两个参数
· data
传递的数据,在传递参数的时候需要使用JSON.stringify()方法将对象参数序列化
· origin
目标的源,协议,主机,端口号
将主页面和次级页面分别用node或者其他方法启动起来查看效果
详细说明在代码注释中
主页面
<body>
<input type="button" value="点击发送数据到postmessage_01.html" onclick="sendInfoToAnotherDomain();"/>
<iframe width="1200" src="//localhost:8180"></iframe>
<script>
function sendInfoToAnotherDomain(){
var personInfo= new Object;
// 要发送的数据
personInfo.name='Yuelu';
personInfo.title='Hello';
personInfo.info="World";
var str=JSON.stringify(personInfo);
// 获取iframe
var iframe=window.frames[0];
/**
* [http description]
* @type {[type]} 要发送的数据, 目标url
*/
// 传递数据
iframe.postMessage(str,'//localhost:8180');
}
</script></body>次级页面(iframe)
<body onload="receiveInfoFromAnotherDomain();"> <p>postmessage_01</p></body><script>
function receiveInfoFromAnotherDomain(){
//监听窗口对象的message事件
window.addEventListener("message",function(ev){
//判断是否来自指定的url
if(ev.origin !="//localhost:8080"){
console.log("the event doesn't come from Domain1!");
return;
}
console.log(ev.data);
//将json字符串转为json对象
var personInfoJSON = JSON.parse(ev.data);
var name = personInfoJSON.name;
var title = personInfoJSON.title;
var info = personInfoJSON.info;
//构造信息文本并显示
var personInfoString="从域为: "+ev.origin+"那里传来的数据."+"<br>";
personInfoString+="姓名是: "+name+"<br>";
personInfoString+="标题为: "+title+"<br>";
personInfoString+="信息为: "+info+"<br>";
document.body.innerHTML=personInfoString;
}
本文由职坐标整理发布,欢迎关注职坐标WEB前端HTML5/CSS3频道,获取更多WEB前端知识!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号