JavaScript: changing the banner code

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

Today I am including script -tag inline in code like:

<script type="text/javascript" src="http://banner.com/b?id=1234"></script>

      

But what the code that uses document.write returns is 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 the code to a div element in DOM ready.

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

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

      

Can JavaScript prototypes handle something like this?

Edit . It should be somewhat waterproof cross-platform, cross-browser compatible, so I don't know if changing document.write is supported.

0


source to share


3 answers


Yes, you can override document.write. Prototyping is not required, you can do it directly on the document itself. I usually do this for malware analysis, but it can of course be used to capture the output of the script declarations, as long as the script declaration doesn't do any particularly complex processing that would increase the difference between document.write and what you replaced it with.

Here's a wrapper that loads ad load (a bit later on 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>

      

+1


source


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

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

      



Then include the script file, then do

document.write = foo;
alert(bannerCode);

      

+1


source


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

$.ready(function() {

});

      

Then you can easily manipulate the element using

$("#div_id").html

      

-1


source







All Articles