股墓山庄

专注于AS3,JavaScript 每天一点进步,坚持...
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

iframe 跨域传值

Posted on 2019-12-26 14:56  股墓山庄庄主  阅读(265)  评论(0编辑  收藏  举报
<iframe :src="iframesrc" id="myIframe" ref="myIframe" width="100%" :height="myIframeHeight" frameborder="0" :onload="autoHeight()"></iframe>
A页面
export default {
    data() {
      return {
        myIframeSrc:undefined,
        myIframeHeight: 50,
            myIframeSrc: "",
            temHeight:0,
      }
    },
    computed:{
      iframesrc:function(){
      //let iframesrc = "http://localhost:9524/tmp-screen/index.html"
      let iframesrc = window.location.protocol+'//'+window.location.host+'/tmp-screen/index.html';
      return iframesrc
      }
    },
    watch: {
      myIframeHeight(newValue, oldValue) {
       // console.log(newValue, oldValue,"A页面——————————————————————————-")
        this.myIframeHeight = newValue
      },
    },
    created() {
        // 得到B传来的值 
        window.addEventListener('message', function (e) {
            
            this.temHeight = e.data
            this.myIframeHeight = e.data
           // console.log("B DOM的高度", this.myIframeHeight)
            document.getElementById('myIframe').height=this.myIframeHeight+"px"
        }, false);
        // 监听A页面的事件,发送给B
        window.addEventListener('scroll', function () {
            let iframe = document.getElementById('myIframe');
            if (!iframe) {
                return;
            }
            // 下拉距离
            let scrollTop = window.pageYOffset ||
                document.documentElement.scrollTop ||
                document.body.scrollTop ||
                0;
            // 窗口高度
            let windowHeight = window.innerHeight ||
                document.documentElement.clientHeight ||
                document.body.clientHeight;
            let json = {
                scrollTop: scrollTop,
                windowHeight: windowHeight,
            };
            iframe.contentWindow.postMessage(json, '*');
        });
    },
    
  }

  B页面

 

data() {
        return {
        Bdata:-1,

        }
    },
   mounted() {
        // 获取到B页面的值,发送给A
        let _this = this
        let b_pageH = document.getElementById('app').scrollHeight;
        this.Bdata = b_pageH;
    
        window.parent.postMessage(this.Bdata, '*');
        // 得到A页面的值
        window.addEventListener('message', function (e) {
         //   console.log("e.data.scrollTop", e.data.scrollTop)
          //  console.log("e.data.windowHeight", e.data.windowHeight)
        }, false);

        window.addEventListener("load", function () {
             let b_pageH = document.getElementById('app').scrollHeight;
             window.parent.postMessage(b_pageH, '*');
          
        });
    }