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

同一个 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;
      }
    }
  })
posted @ 2017-08-24 19:30  coderAngus  阅读(361)  评论(0)    收藏  举报