Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MessageChannel 管道通信 #9

Open
twosugar opened this issue Jun 12, 2019 · 0 comments
Open

MessageChannel 管道通信 #9

twosugar opened this issue Jun 12, 2019 · 0 comments

Comments

@twosugar
Copy link
Owner

twosugar commented Jun 12, 2019

一般用于页面与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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant