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.
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):