javascript - 如何获取iframe元素的innerHTML内容

标签 javascript html google-chrome iframe google-chrome-extension

您好,我正在尝试获取 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/

相关文章:

javascript - 如何知道请求何时开始?

javascript - 如何在 ReactJS 中设置图片 url

html - img 上不透明度的 CSS 关键帧动画不起作用

html - 固定导航栏与 iPhone 版 Chrome 浏览器顶部分开

javascript - 未捕获的类型错误 : undefined is not a function

javascript - 将 html 中的文本 append 到不同的部分

VB Razor 中 &lt;script&gt; 元素中的 Javascript 代码

html - 过渡不适用于不透明度

html - 使用先前表单中的变量更新 HTML 表单

html - Flash 上的 anchor 标记在 Chrome 中不起作用