5

2 つの HTML ファイルがあります。postMessage1 つの HTML ファイルで、HTML5を使用してメッセージを投稿しています。ロード時に投稿されたメッセージを別の HTML ファイルで取得するにはどうすればよいですか?

One.html

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

        <script language="javascript">
            $(document).ready(function() {
                //post message
                var iframeWin = document.getElementById("iframe_id").contentWindow;
                iframeWin.postMessage("helloooo");
            });
        </script>

        <title>IFrame Example</title>
    </head>
    <body>
        <input id="myInput" type="hidden" value="IDDUSER">

        <iframe name="iframe" id="iframe_id" src="Two.html" height="150"></iframe>
    </body>
</html>

Two.html

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

        <script language="javascript">
            $(document).ready(function() {
                //Get posted message here
            });
        </script>

        <title>IFrame Child Example</title>
    </head>

    <body>
        <p id="received-message">I've heard nothing yet</p>
        <h1>Iframe</h1>
    </body>
</html>
4

3 に答える 3

2

子 iframemessageのオブジェクトでイベントをリッスンする必要があります。windowまた、postMessageメッセージとドメインの 2 つのパラメータを取ります。

One.html

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

    <script language="javascript">
      $(document).ready(function() {
        $('#clickMe').click(function() {
          //post message
          var iframeWin = document.getElementById("iframe_id").contentWindow;
          iframeWin.postMessage("helloooo","*");
        });
      });
    </script>

    <title>IFrame Example</title>
  </head>
  <body>
    <input id="myInput" type="hidden" value="IDDUSER">
    <button id="clickMe">Click Me</button>

    <iframe name="iframe" id="iframe_id" src="Two.html" height="150"></iframe>
  </body>
</html>

Two.html

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

    <script language="javascript">
      $(document).ready(function() {
        $(window).on('message', function(evt) {
          $('#received-message').html(evt.originalEvent.data);
        });
      });
    </script>

    <title>IFrame Child Example</title>
  </head>

  <body>
    <p id="received-message">I've heard nothing yet</p>
    <h1>Iframe</h1>
  </body>
</html>
于 2013-08-05T10:23:06.450 に答える