How to get innerHTML content of iframe element
Hi i am trying to get an inner HTML iframe element
my html document structure is like this
<body>
<div>
<iframe id="frame1">
<html>
<button id="mybutton">click me</button>
</html>
</iframe>
</div>
</body>
I am creating a chrome extension, I have to show a warning, when a button named mybutton is clicked, I write a content script
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") ;
I have installed this extension in chrome, when I visit the page then the document body will be changed to an iframe with a button in it. but i came across a warning that has a button but has a button in the iframe, why am i getting null for this button?
source to share
To get the button inside the iframe this might work:
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
Obviously you can go to what you want with help iframeDocument
and use .innerHTML
as you think. You cannot get the content of an iframe if the iframe points to a domain other than its parent.
UPDATE:
You need to use code to get the frame document and its content after , so you should use something like this:
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);
};
DEMO: http://jsfiddle.net/nqTnz/
What matters is how elements are created and added to the DOM, not just using innerHTML
. The onload
iframe method must ensure that it is ready. The actual manipulation code won't work in jsFiddle because of cross-domain issues, but that's what you need.
source to share
In jQuery source code, the solution to get the iframe document looks like this:
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
And then you can usually use getElementsByTagName
or getElementById
to select DOM-Elements:
var elem;
if (iframeDocument) {
elem = iframeDocument.getElementById('mybutton');
}
source to share