父页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <button onclick="addClick()">發送消息</button> <iframe src="http://localhost:9008/iframeTest/" id="testIframework" ></iframe> <script> function addClick() { let dom = document.querySelector("#testIframework"); dom.contentWindow.postMessage( { a: "q2w3qwe" }, "*" ); } </script> </body> </html>
子页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> 這是一個子頁面 <span id="msgContnet"></span> <script> // document.getElementById('msgContnet').innerText window.onload = function () { window.addEventListener("message", function(data){ debugger; }); }; </script> </body> </html>