Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get innerHTML content of iframe element

hi i am trying to get inner HTML of iframe element

my html document a 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 an alert when button with id mybutton is clicked i write an 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 installed this extension in chrome when i visit a page then document body is changed into an iframe with a button in it. but i am facing an alert which has button is null but there is button in iframe why i am getting null for this button??

like image 759
Ritesh Mehandiratta Avatar asked Feb 17 '23 13:02

Ritesh Mehandiratta


1 Answers

To get the button inside of the iframe, this could work:

var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");

Obviously, you can navigate to get what you want with iframeDocument, and use .innerHTML as you seem to know. You cannot get the contents of the iframe if the iframe is pointing to a domain other than its parent.

UPDATE:

You need to use the code to get the frame's document and its contents after it's ready, 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/

The important thing is how the elements are created and appended to the DOM - not just using innerHTML. The onload method of the iframe is to guarantee it's ready. The actual manipulation code won't work in the jsFiddle because the cross-domain problems, but is what you should need.

like image 66
Ian Avatar answered Feb 20 '23 02:02

Ian