PostMessage - 从iframe到Parent的曲面

时间:2014-01-07 22:11:57

标签: javascript html iframe postmessage

我有一个包含iframe的网站。我想跟踪用户在iframe中单击的按钮,并将该信息显示到父窗口。我查看了HTML5 PostMessage,但我不确定如何告诉父母所在的iframe(iframe.html中的第3行)。请注意,父级和iframe具有相同的域和协议。

Iframe.html的

<script type="text/javascript">
    var domain = window.location.protocol + '//' + window.location.hostname;
    var parent = document.getElementById('parent').contentWindow; //what to do?

    $('div').click( function() {
        var message = $(this).text();
        parent.postMessage(message,domain);
    });
</script>

<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>

parent.html

<script type="text/javascript">
    window.addEventListener('message', function(event) {
        if(event.origin !== window.location.protocol + '//' + window.location.hostname;) {
            return;
        }
        $('.message').html(event.data);
    },false);
</script>

<div>
    You have clicked on <span class="message"></span>
</div>
<iframe src="/iframe.html"></iframe>

1 个答案:

答案 0 :(得分:1)

我不确定如何在jQuery中执行此操作,但是,这是在JavaScript中使用父级和子级框架进行通信的本地方式。

关键代码是:

var div = top.document.getElementById("topDiv");

其中top是父框架。

<强> Parent.html

<!DOCTYPE html>
<html>
   <head>
      <title>Parent</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <script>
         function message() {
            var child = document.getElementById("childFrame"),
                    div = child.contentWindow.document.getElementById("childDiv");
            div.innerHTML = "TEXT";
         }
         function main() {
            document.getElementById("messenger").addEventListener("click", function() {
               message();
            });
         }
         window.onload = main;
      </script>
   </head>
   <body>
      <iframe id="childFrame" src="child.html"></iframe>
      <button id="messenger">Click Me</button>
      <div id="topDiv"></div>
   </body>
</html>

<强> Child.html

<!DOCTYPE html>
<html>
   <head>
      <title>Child</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <script>
         function message() {
            var div = top.document.getElementById("topDiv");
            div.innerHTML = "TEXT";
         }
         function main() {
            document.getElementById("messenger").addEventListener("click", function() {
               message();
            });
         }
         window.onload = main;
      </script>
   </head>
   <body>
      <div id="childDiv"></div>
      <button id="messenger">Click Me</button>
   </body>
</html>