var...">

Unable to change iFrame content in Firefox 4 / IE

I have the following code:

<html>
<head>
</head>
<body>
    <script type="text/javascript">
        var frame = document.createElement('iframe');
        frame.id = 'myFrame';
        document.getElementsByTagName('body')[0].appendChild(frame);
        var context = frame.contentWindow.document;
        context.body.innerHTML = 'testing';
    </script>
</body>
</html>

This creates a simple iframe containing my text: 'testing'.

This works fine in Chrome, but Firefox and IE create an empty iframe.

Any idea what I'm doing wrong?

+3
source share
3 answers

You can do something like this:

var frame = document.createElement('iframe');
frame.id = 'myFrame';
document.getElementsByTagName('body')[0].appendChild(frame);

frame = (frame.contentWindow) ? frame.contentWindow : (frame.contentDocument.document) ? frame.contentDocument.document : frame.contentDocument;
frame.document.open();
frame.document.write('testing');
frame.document.close();

Javascript is interpreted differently by all browsers, so it just takes a general approach. This should work in all browsers.

Give it a try.

+2
source

Some browsers explicitly prevent such things, so you cannot, for example, load a bank’s website into a frame and interact with it in Javascript. This link:

http://spyder.wordpress.com/2006/05/31/hacking-around-firefox-security-in-order-to-actually-accomplish-something/

, , iframe, :

http://www.iframehtml.com/iframe-security.html

, .

+1

The rewritten last line of innerHTML seems chrome single.

<script type="text/javascript">        
    var frame = document.createElement('iframe');        
    frame.id = 'myFrame';        
    document.getElementsByTagName('body')[0].appendChild(frame);        
    var context = frame.contentWindow.document;        
    context.write('testing');    
</script>

JS fiddle confirms that it works in IE, Chrome and Firefox:

http://jsfiddle.net/thebeebs/mDMaj/

0
source

All Articles