Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Adsense Insertion With JavaScript

I can't believe how hard this is to find, but even in the Google developer docs I can't find it. I need to be able to dynamically, only with JavaScript insert adsense. I also looked on StackOverflow and some others have asked this but no response. Hopefully this will be a better explanation and will get some replies.

Basically, a user inserts my script, lets call it my.js (can't say what it is specifically at the moment.) my.js is loaded and in my.js some embedded media is displayed on their page then I need somehow to append the generated HTML from:

<script type="text/javascript"><!-- google_ad_client = "ca-pub-xxx"; /* my.js example Ad */ google_ad_slot = "yyy"; google_ad_width = 468; google_ad_height = 60; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> 

Inside a specific <div> (or whatever) element. Any ideas?

P.S. No libraries like jQuery, and I can't insert HTML onto the page unless it's through JavaScript and it has to be inserted into a specific <div> i named (I'm using Sizzle for my JS library if that helps)

like image 864
Oscar Godson Avatar asked Jun 01 '11 07:06

Oscar Godson


Video Answer


1 Answers

The simple technique used to asynchronously load the AdSense script proposed by other answers won't work because Google uses document.write() inside of the AdSense script. document.write() only works during page creation, and by the time the asynchronously loaded script executes, page creation will have already completed.

To make this work, you'll need to overwrite document.write() so when the AdSense script calls it, you can manipulate the DOM yourself. Here's an example:

<script> window.google_ad_client = "123456789"; window.google_ad_slot = "123456789"; window.google_ad_width = 200; window.google_ad_height = 200;  // container is where you want the ad to be inserted var container = document.getElementById('ad_container'); var w = document.write; document.write = function (content) {     container.innerHTML = content;     document.write = w; };  var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://pagead2.googlesyndication.com/pagead/show_ads.js'; document.body.appendChild(script); </script> 

The example first caches the native document.write() function in a local variable. Then it overwrites document.write() and inside of it, it uses innerHTML to inject the HTML content that Google will send to document.write(). Once that's done, it restores the native document.write() function.

This technique was borrowed from here: http://blog.figmentengine.com/2011/08/google-ads-async-asynchronous.html

like image 153
Johnny Oshika Avatar answered Sep 28 '22 05:09

Johnny Oshika