I have an OpenSocial application, and wanted to try AdSense in it. I can easily run Javascript, but cannot include HTML snippets directly. For this reason I am trying to come up with a script that would create a DIV that contains the AdSense ad.
function adsense(w, h, slot) {
google_ad_client = "pub-4815352041522054";
google_ad_slot = slot;
google_ad_width = w;
google_ad_height = h;
var url = "http://pagead2.googlesyndication.com/pagead/show_ads.js";
document.write(
'<div style="border:solid 3px red;">'
+ '<sc' + 'ript src="' + url + '">'
+ '</sc' + 'ript>'
+ 'The ad should be inside the same box as this text.</div>'
);
}
adsense(160, 600, 5133629129);
The code above will write a div with a red border and place the AdSense unit inside of it. This works fine on Chrome, but on IE the referenced AdSense code seems to run after the div has already closed.
I'd like to be able to create AdSense units dynamically from code (for example for A/B testing purposes) and reposition them as required. Any ideas on how to get this to work?
It's too late now, obviously, but I had the same issue and I asked it on StackOverflow (going to be posting the long form answer soon on there too) but the only thing you can really do is load it in an iframe.
Step 1
Create an HTML file on your server with your adsense code like:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-xxxxxxxxxxxx";
/* Some Ad */
google_ad_slot = "xxxxxxxxx";
google_ad_width = 468;
google_ad_height = 60;
//--></script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
Step 2
In that same HTML file you just created, at the top, add:
<style> body {padding:0;margin:0;} </style>
This will make sure there is no spacing in the iframe and the ad code fits snuggly against the border of the iframe.
Step 3
Dynamically add the iframe like:
var insertAdsenseIframe = function(src,width,height){
var iframe = document.createElement('iframe');
iframe.setAttribute("frameborder","0");
iframe.setAttribute("src", src);
iframe.setAttribute("width", width);
iframe.setAttribute("height", height);
return iframe; //Return it so you can use whatever method you want to insert/append
}
var myIframe = insertAdsenseIframe('http://oscargodson.com/dev/scriptTest/cleariframe.html','468px','60px');
document.getElementById('test').appendChild(myIframe);
The JavaScript is just a sample, but works. I never tested in IE or anything. This is just to get you started.
Demo
Because it'd be against the TOS to post this on JSBin then StackOverflow I just created a div in the shape of an ad, but if you put the ad in it'll work.
See: http://jsbin.com/evoqi6/ Hack: http://jsbin.com/evoqi6/edit
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