views:

262

answers:

3

I want to change the behavior of a JavaScript used to display a banner, coming from a central source.

Today I include a script-tag inline in code, like this:

<script type="text/javascript" src="http://banner.com/b?id=1234"&gt;&lt;/script&gt;

But what that returns is code which uses document.write, like this:

if(condition) {
    document.write('<a href="..."><img src="..." /></a>')
}

I want to somehow override this document.write and maybe evaluate the returned code and instead use a JavaScript-framework to bind code to a div-element at DOM ready.

Is there a way to do that? Something like this?:

OnDOMReady() {
    BindBanner(1234);
}
BindBanner(bannerId) {
    var divTag = document.getElementById('banner_' + bannerId);
    divTag.innerHtml = ManipulatedReturenedCode(bannerId);
}

Can JavaScript's prototyping handle something like this?

Edit: It has to be somewhat waterproof cross-platform, cross-browser-compatible, so I don't know if changing document.write is ok.

+1  A: 

Have you tried overriding document.write? I don't have time to try it right now but give this a go:

var foo = document.write;
var bannerCode = '';
document.write = function(str) { bannerCode += str; };

Then include the script file, then do

document.write = foo;
alert(bannerCode);
Greg
A: 

Why not use jQuery? It has a DOM ready function:

$.ready(function() {

});

Then you can easily manipulate an element using

$("#div_id").html
kgiannakakis
Yep, but I have to get the 'html'-object to not document.write, but render the content to html.
Seb Nilsson
+1  A: 

Yes, you can override document.write. Prototyping is not necessary, you can do it directly on the document object itself. I do this commonly for analysing malware, but it could certainly be used to capture ad script output, as long as the ad script doesn't do any particularly convoluted processing that would turn up the difference between document.write and whatever you replaced it with.

Here's a wrapper that loads an ad onload (slightly later than DOMReady):

<div id="advertgoeshere"></div>

<script type="text/javascript">
    function rewrite(w) {
        document.getElementById('advertgoeshere').innerHTML+= w;
    }

    window.onload= function() {
        document.write= rewrite;
        var script= document.createElement('script');
        script.type= 'text/javascript';
        script.src= 'http://externalsite/ads.js';
        document.body.appendChild(script);
    }
</script>
bobince