javascriptdocument.writeadvertisement-server

Is there a way to intercept `document.write`?


I am trying to lazy load some adserver code...

On the page I have this at the moment:

<div class="ad">
    <span>pos_1</span>
</div>

I then go through and pull out all of the ads that should be on the page, call their javascript include file and it gives me this lovely mess:

function do_ad(pos){
    switch(pos){
        case 'pos_1':
            document.write('first ad text');
            document.write('first ad more text');
            //and so on for many many lines
            break;
        case 'pos_2':
            document.write('second ad text');
            document.write('second ad more text');
            //and so on for many many lines
            break;
    }
}

I then want to replace the span with the results of the document.write ad call.

Is there a way to get it to return the string that would have been written to the page?


Solution

  • I don't see why you can't overwrite the document.write function:

    document.old_write = document.write;
    
    document.write = function (str) {
        // lalala
    };
    

    See here: http://www.jsfiddle.net/N9hXy/