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

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

同域名下父子页面通信

  • 父页面
<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>

<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页面

解决方案

尝试:

场景:有三个本地域名,比如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才可以

最终解决方案:

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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值