Rit*_*tta 4 html javascript iframe google-chrome google-chrome-extension
嗨,我想获得iframe元素的内在HTML
我的html文档结构是这样的
<body>
<div>
<iframe id="frame1">
<html>
<button id="mybutton">click me</button>
</html>
</iframe>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
我正在创建一个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") ;
Run Code Online (Sandbox Code Playgroud)
我在访问页面时在chrome中安装了此扩展程序,然后将文档正文更改为iframe,其中包含一个按钮.但我正面临一个警报,其中按钮为空但在iframe中有按钮为什么我为此按钮获取null?
要获取iframe内的按钮,这可能有效:
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
Run Code Online (Sandbox Code Playgroud)
显然,你可以导航以获得你想要的东西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);
};
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/nqTnz/
重要的是如何创建元素并将其附加到DOM - 而不仅仅是使用innerHTML.onloadiframe 的方法是保证它已准备就绪.实际的操作代码在jsFiddle中不起作用,因为跨域问题,但是你应该需要的.
| 归档时间: |
|
| 查看次数: |
20029 次 |
| 最近记录: |