tracking external links with(out) AJAX
2005-9-14
Here's something that would have been an anti-Ajax rant some time ago, but now is more of a K.I.S.S. thing now.
I recently needed some JavaScript to track users leaving a webpage by following links to external pages. So the server-logs would be out. I had a rather good idea of how it could work but couldn't get it to work reliably. Googling I found this blog-post:
That code worked nicely, but had the problem of requiring an Ajax lib for Browsers not able of XMLHttpRequest (basically all IE). That seemed like a big effort for my humble needs, so I sat back down and fixed my code. And now it works wonderfully. And would have done so even in pre-Mozilla/Safari days. The img
object is your friend!
// tracking of external URLs // unobstrusive DHTML/JS // no changes to the HTML source of a webpage needed // May 2005 Martin Spernau (martin AT traumwind DOT de) // just include this script in the head section of a page // external links will be tracked via a // request for a dummy GIF with the actual URL as path-param // Add an eventListener to browsers that can do it somehow. function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, true); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } } function trackInit() { var links = document.getElementsByTagName("a"); var externalRex = /^ http[s]*:/i; for (var i = 0; i < links.length; i++) { var link = links[i]; if (externalRex.exec(link.href)) { eval( "var fn = function () {" + "track(this);" + "return false;" + "}" ); addEvent(link,"click", fn ); } } } function track(link) { var url = link.href; var trImg = new Image(); var now = new Date(); trImg.src = "/tracking/dummy.gif/"+url+"?"+now.getTime(); } addEvent(window,'load', trackInit);
Why use Ajax when simple JavaScript might suffice?
Similar
<< daily writers block | designing for Helma.org >>
alles Bild, Text und Tonmaterial ist © Martin Spernau, Verwendung und Reproduktion erfordert die Zustimmung des Authors