3
votes

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.

1
Nice, clear thought out question. While I can't help, I'll definitely +1.christopher

1 Answers

0
votes

I came up with a workaround. I'm sure there's a better solution out there but for the time being this seems to work:

First I manipulate all the script tags in the HTML string so that they won't be executed. I replace the "src" attribute with "xsrc", and all inner text with an "xinnertext" attribute. Then I use iFrameDoc.write(htmlString) method to write the HTML string to the iFrame. The encoding is all correct, and no scripts are executed.

Then I use jQuery to go through all the scripts one by one. I manually recreate a script (iFrameDoc.createElement('script')) and append it to the DOM in the right place (next to the manipulated script tag).

I use load events to make sure that each script is loaded before the next one is executed.

Not optimal but it works in IE8.