介绍
这篇文章给大家分享的是有关html5中怎么解决外链嵌入页面通信问题的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
使用postMessage推送和窗口。addEventListener接收
原理:
发送方使用postMessage方法向接收方推送消息,第一个参数为推送的内容,第二个参数是允许被访问的域名;
接收方通过监听消息的方法接收数据。
<>强实现跨域就需要有两个不同源的服务器咯强>
开始
iframe引入页面(我也是使用这样方式)
<强>父页面(发送方)强>
& lt; script>//这里是发送监听 ,,,,,,,function btnClick (params), { ,,,,,,,,,,,console.log (1111) ,,,,,,,,,,,var iframe =, . getelementbyid (“childframe") ,,,,,,,,,,,iframe.contentWindow.postMessage ({ ,,,,,,,,,,,,,,,文字:& # 39;你收到了没有呀(白天)& # 39;, ,,,,,,,,,,,,,,,action :, & # 39;光# 39;,,//,action :,自定义动作参数,用于接受收消息是的判断 ,,,,,,,,,,,,},,& # 39;http://localhost: 8000/# & # 39;); ,,,,,,,,,, ,,,,,,,} ,, ,,,,,,,function btnClick2 (params), { ,,,,,,,,,,,console.log (2222) ,,,,,,,,,,,var iframe =, . getelementbyid (“childframe") ,,,,,,,,,,,iframe.contentWindow.postMessage ({ ,,,,,,,,,,,,,,,文字:& # 39;你收到了没有呀(黑夜)& # 39;, ,,,,,,,,,,,,,,,action :, & # 39;黑暗# 39;,,//,action :,自定义动作参数,用于接受收消息是的判断 ,,,,,,,,,,,,},,& # 39;http://localhost: 8000/# & # 39;); ,,,,,,,,,,,, ,,,//这是接收子页面返回的监听(当时也是被各种文章搞的很懵圈呀,如果只父页面发送消息不需要在接收子页面的反馈可以不用写这些) ,,,,window.addEventListener(& # 39;消息# 39;,,function (e), { ,,,,,,,,,,,警报(e.data) ,,,,,,,,,,,const data =, e.data; ,,,,,,,,,,,console.log(数据,& # 39;接到你的页面了数据# 39;) ,,,,,,,}), ,,,,,,,,,,,//下面这些都是踩过的坑 ,,,,,,,,,,,//,var iwindow =, iframe.contentWindow; ,,,,,,,,,,,//,var idoc =, iwindow.document; ,,,,,,,,,,,//,,console.log (“window" iwindow);//获取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 [& # 39; myframe& # 39;] .window) ,,,,,,,} ,,,& lt;/script> & lt; body> ,,,& lt; button onclick=癰tnClick(),在点击& lt;/button> ,,,& lt; br/比; ,,,& lt; button onclick=癰tnClick2(),在点击& lt;/button> , ,,,& lt; iframe name=癿yframe", src =癶ttp://localhost: 8000/#/home1 ?类型=light", id=癱hildframe",宽度=?400 px",身高=?00 px"比; null null null null null null null null null null null null null null null null null null null nullhtml5中怎么解决外链嵌入页面通信问题