Skip to content

iframe知识小结之老项目中嵌套Vue单页应用实践

最近公司因结构变动,将重构的一些新项目放到来老系统中,用到了iframe通信知识,故总结此篇。

同域名下父子页面通信

  • 父页面
html
<html>
  <head>
    <script type="text/javascript">
      function say() {
        alert("parent.html");
      }
      function callChild() {
        myFrame.window.say();
        myFrame.window.document.getElementById("button").value = "调用结束";
      }
    </script>
  </head>

  <body>
    <input
      id="button"
      type="button"
      value="调用child.html中的函数say()"
      onclick="callChild()"
    />
    <iframe name="myFrame" id="myframe" src="child/"></iframe>
  </body>
</html>
  • 子页面
html
<html>
  <head>
    <script type="text/javascript">
      function say() {
        alert("child.html");
      }

      function callParent() {
        parent.say();
        parent.window.document.getElementById("button").value = "调用结束";
      }
      console.log(window.location.href);
    </script>
  </head>

  <body>
    <input
      id="button"
      type="button"
      value="调用parent.html中的say()函数"
      onclick="callParent()"
    />
  </body>
</html>

方法调用

父页面调用子页面方法:FrameName.window.childMethod();
子页面调用父页面方法:parent.window.parentMethod(); // window.top或者window.parent.parent来获取顶层对象

DOM元素访问

获取到页面的window.document对象后,即可访问DOM元素

注意事项

要确保在iframe加载完成后再进行操作,如果iframe还未加载完成就开始调用里面的方法或变量,会产生错误。判断iframe是否加载完成有两种方法:

  • iframe上用onload事件

  • 用document.readyState=="complete"来判断

跨域通信

  • 解决方案一 通信方案
  • 解决方案二 使用postMessage

老项目嵌套Vue单页面应用

新项目场景:elementUI+Vue 使用的多tab的页面结构, 旧项目场景:使用iframe作为tab页面

解决方案

尝试:

text
场景:有三个本地域名,比如ABC页面,B是top窗口,A和B分别位于B中,C要和A通信,,使用postmessafe通信,发现总在B页面向A或者C发送数据的时候,总是报"Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://a.b.com') does not match the recipient window's origin ('http://c.e.com')"
解决办法:在子iframe未加载完是不能向子iframe传递数据的,使用iframe.onload才可以

最终解决方案:

text
由于这样传值太过复杂,最后使用websocket解决

参考文章
https://www.cnblogs.com/sydeveloper/p/3712863.html
https://blog.csdn.net/dreamjay1997/article/details/81319304

上次更新于: