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 somewhat interesting (and maybe even useful) to know which of these regions are actually being used, and the other day I realised this can be tracked fairly reliably and non-invasively using a cookie with a very short lifetime 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 finished loading, the tracking 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 lifetime
});

This finds the first ancestor 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 basically a guess that b.html will have loaded completely in 20 seconds—too long and you risk capturing regions from different sessions or browser tabs, too short and you won’t capture regions at all.

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