首先先介绍一下 ififrame 传递消息的关键方法 postMessage
postMessage的使用
一、简介
- postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递
- postMessage(data,origin)方法接受两个参数:
- data :要传递的数据,html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化,在低版本IE中引用json2.js可以实现类似效果,
- origin :字符串参数,指明目标窗口的源,协议+主机+端口号[+URL],URL会被忽略,所以可以不写,这个参数是为了安全考虑,postMessage()方法只会将message传递给指定窗口,当然如果愿意也可以建参数设置为"*",这样可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/";
二、使用
1、子页面向父页面传递消息
<!-- index.html -->
<iframe src="http://127.0.0.1:5500/frame1.html" frameborder="1"></iframe>
<iframe src="http://127.0.0.1:5500/frame2.html" frameborder="1"></iframe>
<script>
window.addEventListener('message',function(e){
console.log(e.data)
},false)
</script>
<!-- frame1.html -->
<h1>iframe1 page</h1>
<script>
window.top.postMessage('message from iframe1');
</script>
2、父页面向子页面传递消息
<!-- index.html -->
<iframe src="http://127.0.0.1:5500/frame1.html" frameborder="1"></iframe>
<iframe src="http://127.0.0.1:5500/frame2.html" frameborder="1"></iframe>
<script>
window.onload = function () {
var frame1 = window.frames[0];
frame1.postMessage('message from parentwindow', '*');
}
</script>
<!-- frame1.html -->
<h1>iframe1 page</h1>
<script>
window.addEventListener('message',function(e){
console.log(e.data)
},false)
</script>
以下是本人在vue大屏项目使用iframe
监听 krpano页面触发的touchstart
事件
-
在 krpano 里 tour.html
iframe里面
// 监听全景图的鼠标按下, 同时传递参数 params document.body.addEventListener("touchstart", function () { window.parent.postMessage({ //参数是对象 params:1, }, '*'); })
-
在vue里
首先要写在script
下面的export default
外面 写一个方法 监听 iframe传过来的值}, }; window.addEventListener("message", function(eve){ console.log(eve.data.params) if(eve.data.params){ window.initAddNum(); } }); </script> <style> .imgFit { object-fit: contain; }
其次在 vue
mounted
生命周期里 执行这个方法mounted() { window.initAddNum = this.initAddNum; }
然后在 vue 里
methods
里写这个方法methods: { initAddNum(){ // 每次拖拽 iframe里面的全景图 就会触发 这个方法,让addNum清0 this.addNum = 0; console.log('hehe') }, }