2009-07-06 118 views

回答

268
var iframe = document.getElementById('iframeId'); 
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document; 

你可以更簡單地寫:

var iframe = document.getElementById('iframeId'); 
var innerDoc = iframe.contentDocument || iframe.contentWindow.document; 

和第一個有效的內部文檔將被退回。

獲得內部文檔後,您可以像訪問當前頁面上的任何元素一樣訪問其內部組件。 (innerDoc.getElementById ...等)

重要提示:確保iframe在同一個域中,否則無法訪問其內部。這將是跨站點腳本。

+4

很好的答案。你知道你可以這樣做:var innerDoc = iframe.contentDocument || iframe.contentWindow.document; //更具可讀性並且意味着相同 – 2009-07-06 18:40:20

+1

是的,我確實知道這一點。 – geowa4 2009-07-06 18:42:51

4
window.parent.document.getElementById("framekit").contentWindow.CallYourFunction('pass your value') 

CallYourFunction()是頁面內的功能和它是功能作用

1

沒有其他的答案被爲我工作。我結束了創建我的iframe中的函數返回我一直在尋找對象:

function getElementWithinIframe() { 
    return document.getElementById('copy-sheet-form'); 
} 

然後調用該函數像這樣來檢索元素:

var el = document.getElementById("iframeId").contentWindow.functionNameToCall(); 
3

不要忘了訪問的iframe加載後加入。沒有jQuery的舊但可靠的方式:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe> 

<script> 
function access() { 
    var iframe = document.getElementById("iframe"); 
    var innerDoc = iframe.contentDocument || iframe.contentWindow.document; 
    console.log(innerDoc.body); 
} 
</script>