Skip to content

MessageChannel 管道通信 #9

Description

@twosugar

一般用于页面与iframe之间通信
index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    <title>Channel messaging demo</title>
  </head>
  <body>
    <h1>Channel messaging demo</h1>
    <p class="output">My body</p>
    <iframe src="./iframe.html" width='480' height='320'></iframe>
  </body>
  <script>
    var channel = new MessageChannel();
    var output = document.querySelector('.output');
    var iframe = document.querySelector('iframe');
    // Wait for the iframe to load
    iframe.addEventListener("load", onLoad);
    

    function onLoad() {
      // Listen for messages on port1
      channel.port1.onmessage = onMessage;
      // Transfer port2 to the iframe
      iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
    }
    // Handle messages received on port1
    function onMessage(e) {
      console.log(e)
      //接收信息
      output.innerHTML = e.data;
    }
  </script>
</html

iframe.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    <title>My page title</title>
  </head>
  <body>
    <p class="output">iFrame body</p>
    <button onclick="sendMessage()">发送</button>
  </body>
  <script>
  var output = document.querySelector('.output');
  window.addEventListener('message', onMessage);
  
  function sendMessage() {
    console.log('data',data)
      data.ports[0].postMessage('Message back from the IFrame');
  }

  function onMessage(e) {
    window.data = e; 
  	output.innerHTML = e.data;
    // Use the transfered port to post a message back to the main frame
  	// e.ports[0].postMessage('Message back from the IFrame');
  }
  </script>
</html>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions