web通信之跨文档通信 postMessage
index.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>web通信之跨文档通信</title> <style> iframe {float:left;width:45%; height:200px; border:1px solid #333;} </style> </head> <body> <div id="main"> <h1>web通信之跨文档通信</h1> <iframe src="iframe1.html"></iframe> <iframe src="iframe2.html"></iframe> </div> </body> </html>
iframe1.html
<!DOCTYPE html> <html > <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>测试iframe</title> </head> <body> <div> <form> <input type="text" placeholder="随便写点什么"/> <input type="submit" value="确认" /> </form> </div> <script> var eleForm = document.querySelector("form"); eleForm.onsubmit = function() { var message = document.querySelector("input[type='text']").value; window.parent.frames[1].postMessage(message, '*'); return false; } </script> </body> </html>
iframe2
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>测试iframe</title> <style> </style> </head> <body> <div id="message"> 尚未接受到信息。 </div> <script> var eleBox = document.querySelector("#message"); var messageHandle = function(e) { eleBox.innerHTML = '接受到的信息是:' + e.data; }; window.addEventListener("message", messageHandle, false); </script> </body> </html>