There is no way to parse document.write() after the page has finished loading (
https://developer.mozilla.org/en/DOM/document.write). Its behavior re-runs document.open() in that case, which resets the existing document object.
In order to fix this, I needed to do quite a bit of thinking outside the box. Here's the code snippet that I came up with. Since we are eval()ing script tags individually, we have the DOM reference of the script itself (from an earlier
getElementsByTagName("script")) and stored it in
window.resetObj. This allows the magic to begin - we replace document.write() with a new function that does the same job, except it uses object references rather than directly writing to the page:
Code:
// store the original document.write for later
var docWriteOrig = document.write;
// redefine document.write
document.write = function(src)
{
// make sure we have a reference to the containing script tag
if (window.resetObj)
{
// create a temporary HTML object (in memory, not rendered)
var dummy = document.createElement("div");
// in order for the document.write data to NOT be treated as plain text,
// add it as the HTML of an existing node
dummy.innerHTML = src;
// make sure the temporary container now has data
if (dummy.hasChildNodes())
{
// the data was converted to nodes, so cycle through them
for (var cn = 0; cn < dummy.childNodes.length; cn++)
{
// place each node in order before the script tag
YAHOO.util.Dom.insertBefore(dummy.childNodes[cn], window.resetObj);
}
}
}
else
{
docWriteOrig(src);
}
};
This fix is included in the next build. To give some perspective, this issue first appeared in 2.0.0 Beta 3, which was released on June 22, 2008.
If anyone wants to reuse this code, probably an easier way to get the script node reference (what's needed to use the object method) is to do something like the following on your page:
HTML Code:
<script type="text/javascript" id="script_instance_1">
<!--
window.resetObj = document.getElementById("script_instance_1");
document.write('your text');
window.resetObj = null;
//-->
</script>
As far as I can tell, there is no way to completely automate it reliably. You need to set the object each time or the original document.write will be called.