iframe 父页面与子页面之间的方法的相互调用

本文介绍了如何在同一个origin下,使用Vue.js项目实现父页面与iframe中的子页面进行交互的方法。父页面可通过iframe.contentWindow访问子页面的Vue实例,反之亦然。此外,还提供了在不同origin下使用.postMessage()进行通信的方案。

同一个 origin 下,父页面可以通过 iframe.contentWindow 直接访问 iframe 的全局变量、DOM 树等,iframe 可以也通过 parent/top 对父页面做同样的事情。不同 origin 下,标准的方法是通过 .postMessage() 互相通信,不标准的方法是利用 location.hash 等奇技淫巧。协议、域名、端口号,共同决定一个 origin 。

父页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Parent Page</title>
        <script language="javascript" type="text/javascript">
            function parenttest() {
                alert("这是父页面的方法!");
            }
            function btnClick() {
                document.getElementById("childframe").contentWindow.childtest();
            }
    </script>
</head>
<body>
   <div style="margin:auto;">
       <h1>This is the Parent Page.</h1>
       <input type="button" value="调用子页面的方法"  onclick="btnClick()"/> 
    </div>
    <div style="margin:auto;">
       <iframe style="width:300px; height:300px;" id="childframe" src="ChildPage.html"></iframe>
    </div>
</body>
</html>

子页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Child Page</title>
    <script language="javascript" type="text/javascript">
      function childtest() {
          alert("这是子页面的方法!");
      }
      function btnClick() {
          window.parent.parenttest();
      }
    </script>
</head>
<body>
   <div style="margin:auto;">
       <h1>This is the Child Page.</h1>
       <input type="button" value="调用父页面的方法" onclick="btnClick()"/> 
    </div>
</body>
</html>

最近在写一个vue项目,关于vue项目中对iframe的操作如下
父页面:

<iframe ref="iframe" src="child.html" @load="loaded"></iframe>

loaded() {
    const app = this.$refs.iframe.contentWindow.app
    console.log(app)
    if (app && app.setContent) {
        app.setContent(this.xml)
      } else {
        window._xml = this.xml
     }
}

子页面:

window.app = new Vue({ ... })

在console的app信息中,我们能看到一个完整的vue实例,里面可以直接操作iframe中的一些方法和数据
或者我们可以在iframe的vue项目中直接获取父页面的值

window.app = new Vue({
    el: '#app',
    data() {
      return {
        xml: null,
      }
    },
    created: function () {
      this.setContent(window.parent.window._xml);
    },
    methods: {
      setContent: function (xml) {
        this.xml = xml;
      }
    }
  })

转载于:https://www.cnblogs.com/pengzhixin/p/7424898.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值