contentWindow
執行頁面為 index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> </head> <body> <iframe id="message" src="index2.html" frameborder="0"></iframe> <script> window.onload = () => { var iframe = document.getElementsByTagName("iframe")[0]; console.log(iframe.contentWindow.document.getElementById("myid").innerText); } </script> </body> </html>
iframe 頁面為 index2.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> </head> <body> <p id="myid">aaa</p> </body> </html>
執行畫面為
Tip:由於此範例有用到 iframe,故需要於 hosted 主機執行,才可以正常跑出結果。