有些业务场景(比如单点登录)下,我们依然会用到 iframe 这种嵌套页面的方式。但因为会涉及跨域、跨页面的问题,导致浏览器的适配就变成了一个问题,以下纪录了这种问题的解决方案,供大家参考。

<iframe
   :src="iframeUrl"
   id="myframe"
   frameborder="0"
   @load="loaded"
   width="100%"
   height="100%"
 ></iframe>

我们可以通过设置 load 事件确保加载完成之后再执行适配方案。

loaded(type) {
      let scale = 1;
      let iframeWin = document.getElementById("myframe");
      let width = window.screen.width;
      if (
        (width == 1536 && window.devicePixelRatio == 1.25) ||
        (width == 1280 && window.devicePixelRatio == 1.5)
      ) {
        scale = 1 / window.devicePixelRatio;
      } else if (window.devicePixelRatio > 1.5) {
        scale = window.devicePixelRatio / 2.6;
      }
      iframeWin.contentWindow.postMessage(
        {
          title: "XX",
          zoom: scale,
        },
        "*"
      );
    },

需要注意的是,这里我们使用了 contentWindow.postMessage 来传递数据,如果不涉及跨域问题的话,可以直接更改样式或者在 css 中修改。

iframeWin.style.transfrom = `scale(${scale})`;