I'm in a situation where I need to add an advertisement script tag dynamically.
The ad itself is just a simple script tag with the src attribute pointing to the ad server. The actual code which is then ran is a 2-step ordeal:
First, there is a document.write(), like so:
document.write("<iframe id='lctopti2017041855' src='about:blank' style='visibility: hidden;' onload=\"this.style.visibility='visible';\" style='border: 0px; overflow-x: hidden;overflow-y: hidden; width: 100px; height: 400px;' width='100' height='400' scrolling='no' frameborder='0' allowtransparency='true'></iframe>");
Next, there is a:
document.getElementById('lctopti2017041855').src = 'http://www.reallylongurl.com/blah.php?whatever=whatever'
Now, it seems that running document.write() as the page is loading is fine; but I've discovered that if I took the same initial tag and popped it inside of $('#somediv').prepend(), for instance, it would overwrite the entire page.
Is there any way to deal with this? The iframe id and the subsequent ad urls are always dynamic, and generated when the initial script tag requests the javascript from the ad server. If the initial script tag had all the information I needed, I could simply switch out document.write with $('#anywhere').prepend() or something. How can I solve this, short of literally scraping the results of the initial script load and then working with the result?
Is there a way to stop document.write() from overwriting the page but instead only writing where it was called?
Here is something I have successfully done before
var oldWrite = document.write;
var wHtml="";
document.write=function(str) {
wHtml+=str;
}
// load adcode
$('#somediv').prepend(wHtml);
// optionally reset
document.write = oldWrite;
This may fail if the adcode loads a script using document.write too. In that case use an iFrame since it will contain all the crap they can do
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With