I want to use JavaScript to write a full HTML document to an iframe. The following solution works nicely in most cases:
var iFrameDoc = iFrame.contentDocument || iFrame.contentWindow.document;
iFrameDoc.open();
iFrameDoc.write(htmlString);
iFrameDoc.close();
However, if the HTML document contains references to external scripts, and the browser is IE (using IE8 for testing, not sure about other versions), it fails. For example, a HTML document like this:
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<script>alert(variableFromExternalScript)</script>
</body>
</html>
In Firefox and Chrome the above works fine, but in IE8 it fails because the external script is not executed.
I found a workaround which looks like this:
iFrame.contentWindow.contents = htmlString;
iFrame.src = 'javascript:window["contents"]';
That seems to work in all major browsers. The external scripts are loaded as they should be. However, if the HTML document contains any special special characters (such as Chinese), the text ends up garbled in IE. Everything is UTF-8, it works well in other browsers, and IE is set to render the page in UTF-8, but the text in the iFrame is garbled.
So, I have one solution that displays text with the correct encoding, but doesn't load external scripts; and another solution which loads external scripts, but garbles the text. Any suggestions for a solution which solves both issues?
The HTML Document is dynamically loaded so I can't make changes to it such as removing the external scripts.