您好,我正在尝试获取 iframe 元素的内部 HTML
我的html文件结构是这样的
<body>
<div>
<iframe id="frame1">
<html>
<button id="mybutton">click me</button>
</html>
</iframe>
</div>
</body>
我正在创建一个 chrome 扩展我必须在单击 ID 为 mybutton 的按钮时显示警报我写了一个内容脚本
var greeting = "hola, ";
document.body.innerHTML='<div><iframe id="frame1" src="http://onemoredemo.appspot.com/"></iframe></div>' ;
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document
var button = iframeDocument.getElementById("mybutton") ;
if(button ==null)
alert("button is null") ;
当我访问一个页面时,我在 chrome 中安装了这个扩展,然后文档正文被更改为一个带有按钮的 iframe。 但我正面临一个按钮为 null 的警报,但 iframe 中有按钮为什么我为该按钮获取 null??
最佳答案
要在 iframe 中获取按钮,这可以工作:
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
显然,您可以使用 iframeDocument
导航以获得您想要的内容,并使用您似乎知道的 .innerHTML
。如果 iframe 指向其父域以外的域,则无法获取 iframe 的内容。
更新:
准备就绪后,您需要使用代码获取框架的文档及其内容,因此您应该使用如下代码:
window.onload = function () {
var greeting = "hola, ";
var div1 = document.createElement("div");
var frame1 = document.createElement("iframe");
frame1.id = "frame1";
frame1.onload = function () {
alert("loaded");
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
if (button == null) {
alert("button is null");
}
};
frame1.src = "http://onemoredemo.appspot.com";
div1.appendChild(frame1);
document.body.appendChild(div1);
};
演示: http://jsfiddle.net/nqTnz/
重要的是如何创建元素并将其附加到 DOM - 而不仅仅是使用 innerHTML
。 iframe 的onload
方法是为了保证它就绪。由于跨域问题,实际操作代码在 jsFiddle 中不起作用,但这是您应该需要的。
关于javascript - 如何获取iframe元素的innerHTML内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14824739/