demo地址:https://mdn.github.io/dom-examples/channel-messaging-basic/
原文来自:https://developer.mozilla.org/zh-CN/docs/Web/API/MessageChannel
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> <link rel="stylesheet" href=""> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <h1>Channel messaging demo</h1> <p class="output">My body</p> <iframe src="./page.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) { output.innerHTML = e.data; } </script> </html>
page.html (iframe嵌入的页面)
<!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> <link rel="stylesheet" href=""> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <p class="output">iFrame body</p> </body> <script> var output = document.querySelector(‘.output‘); window.addEventListener(‘message‘, onMessage); function onMessage(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>