views:

111

answers:

3

Hi,

I would like to load the content of an iframe with JavaScript. I don't want to change the src but directly the content with:

document.getElementById('frame').contentDocument.body.innerHTML = data;

It works but the JavaScript in data is not executed. Is it a security protection or I forgot something?

+1  A: 

It looks like the problem is not the iframe, but the fact that scripts are not executed when inserted into the DOM text with innerHTML.

You may want to check the following Stack Overflow post for a couple of solutions:

Daniel Vassallo
Problem is that I get a HTML page and can't modify it.
charles
Your best bet is to use a JavaScript framework like jQuery to do the AJAX call. The `jQuery.ajax()` is able to evaluate JavaScript code very easily. You may want to check the following SO post for further info: http://stackoverflow.com/questions/2203762/when-loading-an-html-page-via-ajax-will-script-tags-be-loaded
Daniel Vassallo
A: 

Try this

in a page index.html write:

<script type="text/javascript">

    function init() 
    {
        var s = document.createElement("script");

        s.innerHTML="alert('ops');"    

        document.getElementById("frame").contentDocument.getElementsByTagName("body")[0].appendChild(s);
    }

    window.onload = init;
</script>

...

<body>
    <form id="form1">
    <div>
    <iframe id="frame" src="test.html"></iframe>
    </div>
    </form>
</body>

Then simply write test.html like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <title></title>
</head>
<body>

</body>
</html>

and load from a web server index.html and the code works!!

xdevel2000
The problem is that I get a complete HTML page from ajax.I will get a HTML page from html to /html with javascript inside..
charles
But if you get a complete web page you shouldn't insert that in the body tag and so you should change the src property of the frame tag.
xdevel2000
I make a post with ajax and get the page as reponse.
charles
A: 

Having something like the following would work.

<iframe id = "testframe" onload = populateIframe(this.id);></iframe>

// The following function should be inside a script tag

function populateIframe(id) { 

    var text = "This is a Test"
var iframe = getObj(id); 

var doc; 

if(iframe.contentDocument) { 
    doc = iframe.contentDocument; 
} else {
    doc = iframe.contentWindow.document; 
}

doc.body.innerHTML = text; 

  }
cypher