Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppendChild to iframe in IE

Via javascript (a bookmarklet): I need to create an iframe and then add a form to it and then a script that submits the form.

The following works in Chrome, but not in IE:

var i = document.createElement('iframe'); // also give it id = iframe_id
var frm = document.createElement('form');  // also add inputs and values
var s = document.createElement('script'); // also add innerHTML that submits form 

document.body.appendChild(i);
window.frames['iframe_id'].document.getElementsByTagName('body')[0].appendChild(frm);
window.frames['iframe_id'].document.getElementsByTagName('body')[0].appendChild(s);

In IE I get an error: Unable to get property 'appendChild' of undefined or null reference

I tried to append the form and script to the iframe, before adding the iframe to the document:

 i.appendChild(frm);
 i.appendChild(s);
 document.body.appendChild(i);

I get a weird response in Chrome. The response from the form submit appears in a blocked pop-up (instead of not at all, which I expect). In IE nothing much seems to happen.

like image 406
user984003 Avatar asked Mar 24 '23 03:03

user984003


1 Answers

I'd suggest writing directly to the document using write() initially.

Demo: http://jsfiddle.net/QjPuZ/1/

Code:

var iframeDoc = i.contentDocument || i.contentWindow.document;

iframeDoc.open();
iframeDoc.write("<html><body></body></html>");
iframeDoc.close();

iframeBody = iframeDoc.body;
var frm = iframeDoc.createElement('form');
var s = iframeDoc.createElement('script');
iframeBody.appendChild(frm);
iframeBody.appendChild(s);
like image 184
Tim Down Avatar answered Mar 31 '23 20:03

Tim Down