Friday, February 20, 2009

Add dynamic content to iFrame - IE issues

I need to add dynamic content to an iFrame, and I do not know in advance if this content will be plain text, HTML, JavaScript or a mix. I know that in most instances there will be some JavaScript payload to be executed as part of this content.

I am using a method similar to the one explained by Thomas Bindzus in his blog. This used to work like a charm until a few weeks ago, where it suddenly stopped working in Internet Explorer. Any attempts to do document.write by the content beeing loaded failed. The funny thing is that the payload scripts did execute, but any attempt to add something to the document was ignored by the browser.

After what seems to be hours of playing around, I found out that IE has a problem when closing the document. I modified th logic a bit to avoid closing the document if we are dynamically adding content in IE.

function AddContent(content, frameId)
{
var iframe = document.getElementById(frameId);

var doc = null;
if(iframe.contentDocument) { // Firefox, Opera
doc = iframe.contentDocument;
} else if(iframe.contentWindow) { // Internet Explorer
doc = iframe.contentWindow.document;
var ie = true;
} else if(iframe.document) { // Others?
doc = iframe.document;
}

doc.open();
doc.write(content);
if (
!ie) { // Only close the document for all other browsers, not for IE
doc.close();
}
}

2 comments:

MarPlo said...

Thank you for this article.
It gave me the ideea to solve similar problem.

Tamil Selvan Raman Subramaniam said...

This is awesome !!!