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?
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.
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:
, , iframe, :
http://www.iframehtml.com/iframe-security.html
, .
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: