Javascript iframe 中 Web 元素的 QuerySelector
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26630519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
QuerySelector for Web Elements Inside iframe
提问by snug
Edit: New title. What I'm looking for is a document.querySelector for elements inside an iframe.
编辑:新标题。我正在寻找的是用于 iframe 内元素的 document.querySelector。
I've done quite a bit of Googling for an answer and finally I'm stumped.
我已经做了很多谷歌搜索以获得答案,最后我被难住了。
I'm trying to query inside an iframe. I'm building string selectors to be used in Selenium and usually I just inspect the element with Firebug, and use document.querySelectorAll("theStringIBuid");
我正在尝试在 iframe 内进行查询。我正在构建要在 Selenium 中使用的字符串选择器,通常我只是用 Firebug 检查元素,然后使用 document.querySelectorAll("theStringIBuid");
But it doesn't work with elements inside iframes. I've tried all of the below to get an element "radiobutton1" inside the "page-iframe" iframe.
但它不适用于 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-
谢谢-
回答by cregox
回答by Aero Wang
if the original page's url isn't at the same domain with the iframe content, the javascript will treat the iframe as a black box, meaning it will not see anything inside it.
如果原始页面的 url 与 iframe 内容不在同一个域中,javascript 会将 iframe 视为黑盒,这意味着它不会看到其中的任何内容。
回答by LOAS
Here's a snippet for diving into same-origin frames (ie-compatible ES5):
这是用于深入了解同源帧(即兼容 ES5)的片段:
function findInFramesRec(selector, doc) {
var hit = doc.querySelector(selector);
if (hit) return hit;
var frames = Array.prototype.slice.call(doc.frames);
for(var i = 0; (i < frames.length) && !hit ; i++) {
try {
if (!frames[i] || !frames[i].document) continue;
hit = findInFramesRec(selector, frames[i].document);
} catch(e) {}
}
return hit;
}
This dives into both frameset frames and iframes alike. It may even survive (though not enter) cross origin frames.
这深入到框架集框架和 iframe 中。它甚至可以存活(虽然不能进入)跨原点帧。

