JavaScript: Banner code changing

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"></script>

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.

Answers


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>

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);

Need Your Help

Cannot compile using -std flag with g++

c++ gcc c++11 g++ cygwin

I'm running Windows 7 with cygwin installed and trying to have a play around with some of the newer C++ features. I'm aware that in order to enable these features I have to pass g++ the -std=c++0x...

Including C++ header file with namespace in C source file causes compilation error

c++ c compilation header namespaces

I'm not an expert C++ programmer, and i have been recently doing a trick thing in C++ which is causing me the below issue.