2014-10-29 164 views
3

編輯:新標題。 我在尋找的是iframe中的元素的document.querySelector。iframe中的Web元素的QuerySelector

我已經做了相當多的谷歌搜索答案,最後我很難過。

我想在iframe中查詢。我正在構建Selenium中使用的字符串選擇器,通常我只是用Firebug檢查元素,並使用document.querySelectorAll(「theStringIBuid」);

但它不適用於iframe中的元素。我已經嘗試了下面的所有內容以在「page-iframe」iframe中獲取元素「radiobutton1」。

var elem1 = ".page-iframe"; 
console.log(elem1); 
var elem2 = ".radiobutton1"; 
console.log(elem2); 
document.querySelectorAll(elem1+elem2+""); 

document.querySelectorAll('.page-iframe').contentWindow.document.body.querySelectorAll('.radiobutton1') 
document.getElementById('.page-iframe').contentWindow.document.body.innerHTML; 

[].forEach.call(document.querySelectorAll('.page-iframe'), 
function fn(elem){ 
console.log(elem.contentWindow.document.body.querySelectorAll('.radiobutton1')); }); 

var contentWindow = document.getElementById('.page-iframe').contentWindow 
var contentWindow = document.querySelectorAll('.page-iframe') 
var contentWindow = document.querySelectorAll('.page-iframe')[0].contentWindow 

Thanks-

+0

你或許運行腳本完成的iframe裝載之前?如果你console.log contentWindow,你會得到什麼? – Spokey 2014-10-29 12:38:43

+0

如果你使用硒,你需要調用switchTo().frame(「frame of id」)然後運行你的代碼。 – bcar 2014-10-29 12:52:38

+0

嗯,我一直在這個工作了兩個小時,所以我認爲該頁面已完成加載:) – snug 2014-10-30 08:31:27

回答

3

如果原始網頁的網址是不是在與iframe中的內容相同的域時,JavaScript將把iframe和一個黑盒子,這意味着它不會看到裏面什麼。

4

簡單ES6改編自h3manth

document.querySelectorAll('iframe').forEach(item => 
    console.log(item.contentWindow.document.body.querySelectorAll('a')) 
)