vue 给嵌套的iframe子页面传数据 postMessage

Vue项目中嵌套了第三方的iframe页面,但是需要传递一些数据,如果使用localStorage,因为跨域,这是无法取到的。

只能另寻它法,

那么就用postMessage来传数据:

<iframe src="http://192.168.10.1:8888/index.html" class="utFrame" ref="utFrame"></iframe>

 

 发起传递的页面(俗称父页面)

mounted() {
    this.resetSrc(this.$store.state.iframe.iframeUrl)
    const mapFrame = this.$refs['utiframe']
    if (mapFrame.attachEvent) {
      // 兼容浏览器判断
      mapFrame.attachEvent('onload', function() {
        const iframeWin = mapFrame.contentWindow
        const tInfo = localStorage.getItem('Ut$UserInfo')
        iframeWin.postMessage(tInfo, '*')
        // data传递的参数   *写成子页面的域名或者是ip
      })
    } else {
      mapFrame.onload = function() {
        const iframeWin = mapFrame.contentWindow
        const tInfo = localStorage.getItem('Ut$UserInfo')
        iframeWin.postMessage(tInfo, '*')
      }
    }
  }

接收的页面(俗称子页面)

子页面
<script>
  export default{
    mounted(){
      window.addEventListener('message',function(e){               
            console.log(e.origin,e.data)//子页面接收参数
        })  
     }
}
    

然后就能成功的传递消息了 
同样你能存到localStorage里面使用!好了,问题愉快的解决了

posted @ 2021-01-18 17:11  漠丶然  阅读(1196)  评论(0)    收藏  举报