LATELY — 1 June 2008

Link tracking via JavaScript and Cookies

This site, like just about every other, links to itself from the header, footer and sidebar. It’s some­what in­ter­est­ing (and maybe even useful) to know which of these regions are ac­tu­ally being used, and the other day I re­alised this can be tracked fairly re­li­ably and non-invasively using a cookie with a very short life­time to store the region.

The way it works is, if you’re on a.html and click on a link that takes you to b.html, as you click on the link on a.html, some JavaScript runs that figures out which region you’re in, and writes this to a cookie with a very short lifetime. Then b.html loads as normal. Then, once b.html has fin­ished loading, the track­ing code pulls the region value out of the cookie and sends it on.

The Prototype code to trap clicks:

document.observe(‘click’, function(v) { var e = v.element(); while (e.id == “” && e != document.body) { e = e.parentNode; } Cookie.set(“region”, e.id != “” ? e.id : null, 20); // short life­time });

This finds the first an­ces­tor of the clicked-on element that has a id attribute, and saves that as the region. It is run on every click—not just links—but my site is mostly flat HTML so most clicks do end up as page loads. (If this is not the case, you could add some code to filter out the non-page load clicks.) The 20 seconds is ba­si­cally a guess that b.html will have loaded com­pletely in 20 seconds—too long and you risk cap­tur­ing regions from dif­fer­ent ses­sions or browser tabs, too short and you won’t capture regions at all.

In b.html, the region is ex­tracted with Cookie.get("region"); see init.js (which also defines Cookie.set() and Cookie.get().)