Extraordinary Thoughts
23Jan/106

Adsense and AJAX: A Solution

Tired of fight with Adsense when using AJAX?  That's exactly how I've been the last couple days.  For such a widely spread service, it's terrible how bad flexibility for Web applications can be!

Anyways, most reputable programmers wont be relying much on iFrame, so here's an easy solution - just run this function every time you want to update the ads on your page.

I must warn you, DO NOT abuse this, Google can and will ban your account if impressions are being forced.  I can't vouch that Google will even approve of this method, but from reading the ToS it should be acceptable giver the [end] user sent a request to change page content.

var redirects = 0;
function updateAdsense() {
	redirects++;
	var ads = document.getElementsByTagName('iframe');
	var src;
	if(ads && ads.length){
		for (var i = 0; i < ads.length; i++){
			src = ads[i].src.split('&');
			if(redirects > 1)
				src.pop();
			src = src.join('&');
			src = src + '&'+new Date().getTime();
			ads[i].contentWindow.location.replace(src);
		}
	}
}

You can see I use "location.replace", this solves issues with Adsense updates effecting browser navigation. In basic, it makes the back button work correctly.

As you can see this code is rather lazy, I will be providing an update soon. :)

Update

var redirects = 0;
function updateAdsense() {
	redirects++;
	var ads = document.getElementsByTagName('iframe');
	var src;
	if(ads && ads.length){
		for (var i = 0; i < ads.length && ads[i].id.substr(0,16)=='google_ads_frame'; i++){
			src = ads[i].src;
			if(redirects > 1) {
				src = src.split('&');
				src.pop();
				src = src.join('&');
			}
			src = src + '&'+new Date().getTime();
			ads[i].contentWindow.location.replace(src);
		}
	}
}

Categories

Comment Leaderboard

Links

Meta

Alexa Rank


Blog Directory - OnToplist.com
Clicky Web Analytics

This Blog is DoFollow!

Tags

1080p ajax album art better code cron dd-wrt dhcp dns dnsmasq dslr everun faster firefox gh1 good google graphics html5 laser logitech maximize mouse netbook note optimize panasonic php ping plugin plugins processor review router screen scripts search seo snapshots tcp/ip twitter upgrade video wordpress