If your particular web measurement application doesn’t provide you the ability to measure which links your visitors are clicking, use this simple JavaScript hack to track them yourself.
Before browser overlays, many vendors used JavaScript to track clicks on pages. Since the script is not very complicated and is used in other contexts in this book [Hack #13] , it is also worth presenting as a standalone hack.
To track clicks the old-fashioned way, you simply hijack
JavaScript’s onClick
event handler,
instructing it to fire off a message to a custom variable [Hack
#31] in your measurement application right before
the click is processed. The JavaScript for this is pretty
straightforward; simply include this JavaScript in any page you want
to track clicks on.
<script language="JavaScript"> ' Use random numbers to ensure that the link doesn't get caught in ' the browser cache ' rnum = Math.random() * 1000000; rnum = Math.round(rnum); d=document.location; r=document.referrer; i.onload = SetClickTracking; ' ' After the click is processed, pass the click along as usual ' function ClickTrackRedirect(url){ window.location.href=url; } ' ' When a link is clicked, send a new image request to the measurement application ' NOTE: Your string in the "c.src=" line will differ depending on your particular ' application. Consult your vendor for the specific string you'll need to use ' function ClickAlert(){ c=new Image(); c.src=(http://www.yourtrackingapplication.com/ tracking_code.cgi?link_href="+escape(this.href)+"&rn='+rnums;) c.onload=ClickTrackRedirect(this.href); } ' ' This function sets up the link array and calls ClickAlert when a link is clicked ' Use Language to Drive Action function SetClickTracking(){ for(i=0;(link=document.links[i]); i++){ link.onclick=ClickAlert; }; } </script>
The most important things to note about this code are:
You need to replace (http://www.yourtrackingapplication.com/tracking_code.cgi with the URL you use to identify a page request to your tracking application. Be sure to include any necessary page and account identification to ensure that the click is tracked.
You need to replace the
link_href=
with the necessary code to pass a data to a custom variable [Hack #31] .In most instances, calling this script will increase the page view count for the page at the same time the click is recorded. Consult with your vendor for a workaround to this problem, if necessary
And perhaps most importantly, most modern web measurement applications are able to measure clicks with relatively little setup and will present the results in a more elegant fashion than this code.
—Ian Houston and Eric T. Peterson
Get Web Site Measurement Hacks now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.