2013-05-21 70 views
0

我試圖訪問一個iFrame的內容,我無處可去。爲什麼我可以訪問iFrame而不是其內容?

我有這樣的:

that.findGadget = $.fn.findGadget = function (root) { 
    var root = root || this; 
    if (root[0].tagName === "IFRAME") { 
     root = root[0].contentDocument || root[0].contentWindow.document; 
    } 
    console.log(root); 

};

我呼籲的iFrame本身的功能,像這樣:

// options is my configuration object with id/src/... 
var newHTML = document.createElement("iframe"); 
newHTML.setAttribute("src", options.src); 
newHTML.setAttribute("frameborder", 0); 
newHTML.setAttribute("data-id", options.id); 
// add iFrame to page 
// options.parent is a $(element) 
newParentElement = options.parent.parent()[0]; 
options.parent.replaceWith(newHTML); 

// select 
var newRootElement = newParentElement.querySelectorAll(
    '[data-id="'+options.id+'"]' 
); 
// calling on $('iframe') 
$(newRootElement[0]).findGadget(); 
... 

我好像裏面findGadget作品聲明還好吧,所以root設置爲iframe的document。然而,我從那裏卡住,因爲我想嘗試的一切:

root.body 
root.body.innerHTML 
$(root).find('div'); 
$('iframe').contents(); 

是未定義的或一個空的選擇器。

問題
如何正確訪問iFrame的元素?問題可能是內容尚未加載?我正在研究localstorage,所以所有文件都來自同一個「域」。

感謝您的幫助!

+0

iframe是否完全加載?它在同一個域中嗎? – epascarello

+0

相同的域名:是的。我如何檢查它是否被加載? – frequent

+0

什麼是'options.src'?你提到的本地存儲意味着它可能是一個'data:'URI。 – Quentin

回答

1

對,您需要等到iframe內容加載完畢。使用jQuery:

$('iframe').load(function() {       
    // access the iframe content 
}); 
+0

'load'爲我做了。因爲現在'this'就是包含內容的iframe。謝謝! – frequent

1

考慮以下幾點:

1)我建議你到火findGadget()功能加載IFRAME時。您可以通過iframe的頁面本身內調用它或把整個$(newRootElement[0]).findGadget();實現這一目標到

$(newRootElement[0]).ready(function(){ 
    // here 
}); 

2)我建議只使用contentWindow,因爲它是與所有的瀏覽器完全兼容(測試)。

+0

也感謝您的信息! – frequent

相關問題