document.write() in injected HTML

document.write() in injected HTML


I want to be able to call load() on any HTML, but there is a problem
with HTML that includes JavaScript that uses document.write() . I
think it would be nice if injected HTML would handle document.write()
correctly, so I changed jQuery 1.2.1 to handle this. I hope something
like this can be included in jQuery in the future. (I'm a Java
programmer who isn't very familiar with JavaScript, so I hope the code
isn't too bad.) Here is my fix:
---------------------------
    domManip: function(args, table, dir, fn) {
        var clone = this.length > 1, a;
        return this.each(function(){
            if ( !a ) {
                a = jQuery.clean(args, this.ownerDocument);
                if ( dir < 0 )
                    a.reverse();
            }
            var obj = this;
            if ( table && jQuery.nodeName(this, "table") &&
jQuery.nodeName(a[0], "tr") )
                obj = this.getElementsByTagName("tbody")[0] ||
this.appendChild(document.createElement("tbody"));
            jQuery.each( a, function(){
                var elem = clone ? this.cloneNode(true) : this;
                jQuery.each( evalScript(0, elem), function(i,elem){
                    fn.call( obj, elem );
                });
            });
        });
    }
};
function evalScript(i, elem){
    var script = jQuery.nodeName(elem, "script");
    if ( script ) {
        var buf = "";
        var oldWrite = document.write;
        var oldWriteln = document.writeln;
        document.write = function(){
            for ( var i = 0; i< arguments.length; i++ ) {
                buf += arguments[i];
            }
        };
        document.writeln = function(){
            document.write.apply(document,arguments);
            document.write("\n");
        };
        try {
            if ( elem.src )
                jQuery.ajax({ url: elem.src, async: false, dataType: "script" });
            else
                jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML
|| "" );
        } finally {
            document.write = oldWrite;
            document.writeln = oldWriteln;
        }
        var r = buf.length == 0 ? [] : jQuery.clean([buf],
elem.ownerDocument);
        if ( elem.parentNode ) {
            for( var i = 0; i < r.length; i++ ) {
                elem.parentNode.insertBefore( r[i], elem );
            }
            elem.parentNode.removeChild(elem);
        }
        return r;
    } else if ( elem.nodeType == 1 )
        jQuery("script", elem).each(evalScript);
    return [elem];
}
---------------------------