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

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

$.ready(function() {

});

Then you can easily manipulate an element using

$("#div_id").html

Need Your Help

Can you change the location/endpoint of a dynamic web reference at run-time in .NET?

c# .net dynamic web-services jira

In a fairly standard fashion, I created a Web Reference to a SOAP service in Jira for an extension that I'm building (Jira is an issue tracker for those unfamiliar with it). Visual Studio auto-gene...

NSArrayController of NSManagedObject accesses *array* instead of *set*

cocoa core-data nsarraycontroller

A xib file in my OS X project contains a table view backed by an NSArrayController which is set to Entity Name (aka Core Data) mode. When I send an -add: message to this array controller, an excep...