Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with document.write in a script that's added after a page has loaded?

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?

like image 208
dsp_099 Avatar asked Dec 08 '12 06:12

dsp_099


1 Answers

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

like image 103
mplungjan Avatar answered Oct 02 '22 20:10

mplungjan