Html程序  |  49行  |  1.2 KB

<html>

 <head><title>Post message tests</title>
 <script>
  // Send a message to our opener, and it will reply.
  function postToOpener(msg, origin) {
    window.opener.postMessage(msg, origin);
    return true;
  }

  // Send a message to a window named "foo".
  function postToFoo(msg) {
    var w = window.open("", "foo");
    w.postMessage(msg, "*");
    return true;
  }
  
  // Send a message to a subframe of window named "foo".
  function postToFooFrame(msg) {
    var w = window.open("", "foo");
    w.frames[0][0].postMessage(msg, "*");
    return true;
  }

  // Listen to incoming messages.
  var receivedMessages = 0;
  var receivedMessagesWithPort = 0;
  window.addEventListener("message", messageReceived, false);
  function messageReceived(event) {
    receivedMessages++;
    if (event.data === "2-1-reply") {
      event.source.postMessage("msg4", "*");
    }
    if (event.ports.length > 0) {
      receivedMessagesWithPort++;
      var port = event.ports[0];
      port.start();
      port.postMessage("msg-back-via-port");
      // Change the title to generate a notification.
      document.title = event.data.message;
    } else {
      document.title = event.data;
    }
  }
 </script>
 </head>

</html>