獲取iframe的window對象js代碼如下.注意:一定要在文檔加載完成之后,才能獲取到
var Iframe=document.getElementById("script");//先獲取到iframe元素 var iframeWindow=(Iframe.contentWindow || Iframe.contentDocument);//獲取到指定iframe下window
對應html代碼:
<iframe class="Panel" id="script" src="t.html"></iframe>
以上代碼就能實現獲得頁面中iframe的window對象
現在實現iframe和父頁面通信,
page1(為iframe頁面代碼):
<!DOCTYPE html> <html> <head> <meta charset=utf-8" /> <title>By:DragonDean</title> <script src="jquery.js"></script> <script type="application/javascript"> window.onload=function(){ window.evt=document.createEvent('Event');//創建一個事件,掛在當前頁面的window對象上 window.evt.initEvent('myEvent',true,true);//初始這個事件 var obj=document.getElementById('testBtn'); obj.addEventListener('click', function(){//自定義事件觸發的條件,例子中用的點擊 window.evt.test='測試iframe之間用事件傳數據';//測試傳值 window.dispatchEvent(window.evt);//讓自定義事件觸發 }, false);
console.log(parent);//父頁面的window對象,iframe嵌入頁面自帶
};
</script></head> <body> <button id="testBtn">test</button> </body> </html>
page2(主頁面):
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script> window.onload=function(){ var Iframe=document.getElementById("script");//先獲取到iframe元素 var iframeWindow=(Iframe.contentWindow || Iframe.contentDocument);//獲取到指定iframe下window /*在主頁面對iframe頁面的window上添加一個監聽事件,監聽自定義事件,傳入一個當前頁面的函數,獲取iframe觸發的事件*/ iframeWindow.addEventListener('myEvent',function(event){//event為t.html中觸發這個監聽的window.evt事件 console.log(event.test);//到此,傳值完成 }) } </script> </head> <body> <iframe class="Panel" id="script" style="height: 1000px;" src="page1.html" name="script"></iframe> </body> </html>
將兩個頁面放同目錄下,運行page2,呼出控制台,就能看到傳值結果。