iframe跨域,获取iframe中元素

2021-11-05  本文已影响0人  storyWrite

1.需求让iframe嵌入页面,并且没有滚动条,也就是相当于两个页面拼接在一起

  1. 跨域解决,通过框架配置代理
  proxy: {
    '/medical': {
      target: 'https://example.com',
      changeOrigin: true,
      pathRewrite: {
        '^/medical': '',
      },
    },
  }
  1. 获取iframe宽度,并设置iframe宽度,使其不出现滚动条
  <iframe
        ref="iframe"
        name="sonFrame"
        class="iframe hide-in-large hide-in-medium"
        width="100%"
        :height="height"
        marginWith="0"
        scrolling="no"
        src="/medical/example...."
        frameborder="0"
      ></iframe>

    this.iframe = this.$refs.iframe;
      // iframe加载完成后修改高度
      this.iframe.onload = () => {
        this.height = this.iframe.contentDocument.body.scrollHeight;
      };

主要问题在于跨域之后无法获取iframe中元素,导致高度不获取,无法设置高度

++++++++++++++++++++++++++++++++++++++++++++++++++

  1. 遇到新问题

+++++++++++++++++++++++++++++++++++++++++++++++++++

5.微信浏览器/qq浏览器横屏切换回竖屏字体变大

由于微信浏览器与qq浏览器执行resize回调函数之后第一时间获取到的innerWidth 不是横屏之后的值因此需要,延时获取,然后重新渲染iframe
此时无法使用v-show,即使在resize时第一时间将iframe隐藏,但是iframe字体格式也已经变为了横屏尺寸字体

    <div class="mt-40">
      <!-- 微信/qq浏览器需要重新加载iframe -->
      <iframe
        v-if="!isPc && isWeiXin"
        width="100%"
        marginWith="0"
        scrolling="no"
        src="/medical/ecp-cms/cdn-file/tac/content/WMS/0/TAC_MEDICAL.html"
        frameborder="0"
      ></iframe>
      <!-- 其余浏览器不需要重新渲染 -->
      <iframe
        v-show="!isPc && !isWeiXin"
        width="100%"
        marginWith="0"
        scrolling="no"
        src="example.html"
        frameborder="0"
      ></iframe>


  computed: {
    // 判断是否为微信浏览器/qq浏览器
    isWeiXin() {
      const ua = navigator.userAgent.toLocaleLowerCase();
      return (
        window.navigator.userAgent.includes('MicroMessenger') ||
        ua.match(/tencenttraveler/) != null ||
        ua.match(/qqbrowse/) != null
      );
    },
  },
   window.addEventListener('resize', () => {
        // 微信/qq浏览器 resize时第一时间获得的innerWidth值不是更新后的值,需要延时获取
        const time = this.isWeiXin ? 100 : 0;
        setTimeout(() => {
          this.isPc = window.innerWidth > 719;
        }, time);
      });
上一篇 下一篇

猜你喜欢

热点阅读