1

In an iframe when loading content dynamically, the sequence document.open, document.write, and document.close fails in IE 9, 10, and 11 but succeeds in other browsers. However, if I assign document to a temporary variable and then do open, write, close, IE succeeds. Why is this?

(Yes, I know that there are better options besides document.open/write/close, like jquery and DOM construction, but I am curious why this fails.)

The following files show the problem:

index.htm

<!DOCTYPE html>
<html>
<head>
    <title>Top Window</title>
</head>
<body>
<p>Top Window</p>
<div id="testDiv" style="width: 100%;">
    <iframe src="frame.htm" style="width: 100%;"></iframe>
</div>
</body>
</html>

frame.htm

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
    <p>Waiting...</p>
</body>
</html>

script.js

'use strict';

var getPage = function() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if( (this.readyState == 4) && (this.status == 200) ) {
            writePage( this, "" + this.responseText );
        }
    };

    xmlhttp.open("GET", "content.htm", true);
    xmlhttp.send();
};

var writePage = function( xmlhttp, pageContent ) {
    var tempDocument = document;

    document.open( "text/html" );
    document.write( pageContent );
    document.close();
};

getPage();

content.htm

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h1>This is my written content.</h1>
</body>
</html>

In the writePage function, this sequence does not work (the document.open call does not return):

document.open( "text/html" );
document.write( pageContent );
document.close();

However, using the temporary reference like this:

tempDocument.open( "text/html" );
tempDocument.write( pageContent );
tempDocument.close();

works fine.

dxp
  • 21
  • 3
  • http://stackoverflow.com/questions/1736886/why-wont-this-javascript-using-document-open-and-document-write-work-in-inter may provide some insights. Maybe https://sparecycles.wordpress.com/2012/03/08/inject-content-into-a-new-iframe/ as well – sideshowbarker Sep 21 '15 at 20:01

0 Answers0