سؤال

I have a website that contains an iframe. I want to track which button the user clicks inside the iframe and surface that information to the parent window. I looked into HTML5 PostMessage, but am unsure how I would tell the iframe where the parent is (line 3 in iframe.html). Do note that the parent and iframe have the same domain and protocol.

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>
هل كانت مفيدة؟

المحلول

I'm not sure how to do it in jQuery, however, here is a native way to communicate between parent and child frames in JavaScript.

The key code being:

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

Where top is the parent frame.

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>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top