本文主要介绍html5关于外部链接中嵌入页面的通信问题(postMessage解决跨域通信)。通过示例代码进行了非常详细的介绍,对大家的学习或工作有一定的参考价值。有需要的朋友就跟着下面的边肖学习吧。
说起来挺简单的,可以直接查询postMessage Push和window.addEventListener的用法,最好自己搞清楚。本文只记录你的使用情况。
使用postMessage push和window.addEventListener接收
原则:
发送方使用postMessage方法向接收方推送消息,第一个参数是推送的内容,第二个参数是允许访问的域名;
接收器通过监听信息接收数据。
实现跨域就需要有两个不同源的服务器咯
开始
页面中引入了Iframe(我也使用这种方法)
父页面(发送方)
脚本
//这里是发送监视器。
函数btnClick(params) {
console.log(1111)
var iframe=document . getelementbyid(‘ child frame ‘)
iframe . content window . postmessage({
正文:‘你(白天)收到了吗’,
Action: ‘light’ //Action:用户自定义的action参数,用于接受收到的消息是yes的判断。
},’ http://localhost:8000/#/’);
}
函数btnClick2(params) {
console.log(2222)
var iframe=document . getelementbyid(‘ child frame ‘)
iframe . content window . postmessage({
正文:‘收到了吗(晚上)’,
Action: ‘dark’ //Action:用户自定义的action参数,用于接受接收消息为yes的判断。
},’ http://localhost:8000/#/’);
//这是接收子页面反馈的监测(当时也是被各种文章搞糊涂了。如果只有父页面发送消息,它不需要接收子页面的反馈,所以你不用写这些)
window . addevent listener(‘ message ‘,函数(e) {
警报(电子数据)
const data=e.data
Console.log(数据,“收到您的页面数据”)
})
//下面都是踩出来的坑。
//var iwindow=iframe . content window;
//var idoc=iwindow . document;
//console.log(‘window ‘,I window);//获取iframe的窗口对象
//console.log(‘document ‘,idoc);//获取iframe的文档
//console.log(‘html ‘,idoc . documentelement);//获取iframe的html
//console.log(‘head ‘,idoc . head);//拿人头
//console.log(‘body ‘,idoc . body);//得到身体
//console . log(window . frames[‘ my frame ‘]。窗口)
}
/脚本
身体
按钮onclick=’btnClick()’单击/按钮
br/
按钮onclick=’ BTN Click 2()’ Click/button
iframe name=’ my frame ‘ src=’ http://localhost:8000/#/home 1?type=light ‘ id=’ child frame ‘ width=’ 1400 px ‘ height=’ 800 px ‘
/body
关于发一波简单的解释:
iframe name=’ my frame ‘ src=’ http://localhost:8000/#/home 1?type=light ‘ id=’ child frame ‘ width=’ 1400 px ‘ height=’ 800 px ‘
这里的src是子页面的地址(这里是按照你自己的路由写的或者那个页面需要监听写的地址)。
PostMessage({ text:’你收到了吗(晚上)’,action:’天黑’ },’ 3358localhost: 8000/#/’)
第一个参数是内容,第二个是子页面的地址。这里只能写项目的地址或者写(比如:PostMessage (‘content ‘,’ ‘))。我没试过,但是应该可以。
子页面(接收方+反馈)
我在这里的接收直接写在我的react项目中。
componentWillMount() {
window . addevent listener(‘ message ‘,(e)={
console.log(e)
让=e.data//This是接收的数据
//e.origin这是发送数据的地址。
})
.
.
.
//关于反馈,我在我的项目里写了一个点击动作,发送如下
goCustomerDetail=(data)={
让url=data.url
//window.top.postMessage({
//text:’返回Url ‘,
//url:url
//},’ http://XXX:8083/史策/ceshi.html ‘)
window . top . postmessage(‘ { ‘ name ‘:’ customer details ‘,’ path ‘:’ URL ‘ ‘ } ‘,’ * ‘)
}
解释上面收到的一波反馈:
1.receive window . addevent listener(‘ message ‘,(e)={console.log (e)})
e是整个接收到的消息体有很多内容。拿自己用的数据来说。注意,有些操作要在判断符合条件后进行。
2.发送方式,我自己实验了两种反馈,父页面都能收到。
注意window.top.postMessage的反馈
结束
总结:这个方法还是很好用的。它可以不同于technology stack的通信链路,但是它的安全性不是很好。而且会出现跨域的问题,比如数据请求失败或者接口拦截。你需要自己打开接口,设置一波持续访问。
额外收获:还有其他的介绍方式。我自己没用过。请参考链接分享一下。
https://www.jianshu.com/p/fb579be635b2
https://www.cnblogs.com/Jry666/p/8418643.html
https://blog.csdn.net/monkindey/article/details/23659387
关于html5的外链嵌入页面的通信问题(postMessage解决跨域通信)这篇文章到此为止。关于html5外部链接嵌入式通信的更多信息,请搜索脚本之家之前的文章或继续浏览下面的相关文章。希望大家以后多多支持剧本之家!
来源:剧本之家
链接:https://www.jb51.net/html5/736172.html