iframe跨域通信(设置高度)

主页面html

<iframe width="100%" id="yqiframe" name="sendMessage" src="https://m.abc.cn/test.html" frameborder="0" scrolling="no">iframe>

主页面js

$(function () {
  var ifr = window.frames['sendMessage'];
  var iframeTimer = setInterval(function () {
    console.log('begin')
    ifr.postMessage('getheight', "*");
  }, 500)
  window.addEventListener('message', receiver, false);
  function receiver(e) {
    if (typeof (e.data) == 'number') {
      console.log('clear')
      clearInterval(iframeTimer)
    }
    if (e && e.data) {
      $('#yqiframe').css('height', e.data + 'px')
    }
  }
})

嵌入另一域名页面

sendHeight() {
    window.addEventListener('message', receiver, false);
    function receiver(e) {
        console.log('iframe', e)
        if (e && e.data == 'getheight') {
            setInterval(() => {
                e.source.postMessage(document.documentElement.offsetHeight - 120, e.origin);
            }, 300);
        }
    }
},

你可能感兴趣的:(js,iframe)