1、獲取iframe的window對象
存在跨域訪問限制。
iframeElement.contentWindow 兼容
2、獲取iframe的document對象
存在跨域訪問限制。
chrome: iframeElement.contentDocument
firefox: iframeElement.contentDocument
ie:iframeElement.contentWindow.document(ie沒有iframeElement.contentDocument屬性)
var getIframeDocument = iframeElement.contentDocument||iframeElement.contentWindow.document;
3、iframe中獲得父頁面的window對象
存在跨域訪問限制。
父頁面:window.parent 兼容
頂層頁面:window.top 兼容
4、獲取iframe在父頁面中的html標簽
存在跨域訪問限制。
window.frameElement 兼容
5、iframe的onload事件
非ie瀏覽器都提供了onload事件。例如下面代碼在ie中是不會有彈出框的。
var ifr = document.createElement('iframe');
ifr.src = 'http://www.b.com/index.php';
ifr.onload = function() {
alert('loaded');
};
document.body.appendChild(ifr);
但是ie卻又似乎提供了onload事件,下面兩種方法都會觸發onload
方法一:
<iframe onload="alert('loaded');" src="http://www.b.com/index.php"></iframe>
方法二:
//只有ie才支持為createElement傳遞這樣的參數
var ifr = document.createElement('<iframe onload="alert('loaded');" src="http://www.b.com/index.php"></iframe>');
document.body.appendChild(ifr);
由於iframe元素包含於父級頁面中,因此以上方法均不存在跨域問題。
實際上IE提供了onload事件,但必須使用attachEvent進行綁定。
var ifr = document.createElement('iframe');
ifr.src = 'http://b.a.com/b.php';
if (ifr.attachEvent) {
ifr.attachEvent('onload', function(){ alert('loaded'); });
} else {
ifr.onload = function() { alert('loaded'); };
}
document.body.appendChild(ifr);
6、frames
window.frames可以獲取到頁面中的節點(iframe、frame等),需要注意的是取到的是window對象,而不是HTMLElement。
var ifr1 = document.getElementById('ifr1');
var ifr1win = window.frames[0];
ifr1win.frameElement === ifr1; // true
ifr1win === ifr1; // false
補充:
var iframeObj = document.getElementById('iframeid');
a:獲取子頁面中body里的內容
var iframeContent = iframeObj.contentWindow.document.body.innerHTML;
b:獲取子頁面中head里的內容
var iframeContent = iframeObj.contentWindow.document.head.innerHTML;
c:獲取子頁面中html里的內容
var iframeContent = iframeObj.cententWindow.document.documentElement.innerHTML;
d:獲取子頁面中某個元素里的內容
var iframeContent = iframeObj.contentWindow.document.getElementById('element_id').innerHTML;