19:22 38

Tracking Outbound Clicks

From time to time it may be useful to know what links people are clicking that takes them off your website. Previously it was accepted that having your links in the format "out.php?link=http://...." was the best way to do this, but I've always found that to be a little clunky and not particularly search-engine friendly.

In addition to this, I'm of the school of thought that likes to launch off-site links in their own window. This gives the visitor another indication that they're no longer on your site.

New Windows for Off-Site Links

The first step in the project is to get all of the links on a page and see which ones point to off-site destinations. This is fairly straightforward and is best done after the page has loaded:

All we're doing here is stepping through all of the links and comparing their HREF arguments against a base URL. Any HREFs that don't match our base are set to open in a new window using _blank.

In the above code, base is dest[0] which is the first link on the page - typically your website logo which links to root. If this is not the case with your website, you can replace this with your domain name, however my approach has the benefit of working in whatever environment you're using - dev, subdomain, localhost etc.

Adding the Click Tracking

Since we're now stepping through the links in the site, and we know which ones are pointing off-site, tracking these clicks is simply a matter of programmatically adding an onclick event to each one.

Immediately after the target = '_blank' line, add:

Now, as well as opening in a new window, each off-site link will also call a function called out() with the structure of the link itself element as an argument.

We now need an out() function which spawns an action that we can record, so we'll knock somthing up using that old standby, the hidden IFrame:

All our new function does it accept the link object from the onclick() event and send the href component to a script called out.php, but it does this in a hidden iframe (called 'action') so that the process is completely hidden from to the user. Since our off-site links are opening in new windows anyway, the page containing the iframe won't be changed and the script is free to do it's thing.

Saving the Details

Your out.php can also be very simple - all it needs to do is take the url value from the querystring, sanitise it and store it somewhere. You can also add the date referring page if you want to, and keep a count of the number of hits on each date.

As ever, comments are appreciated. Please let me know if you use this anywhere.



Tested on desktop versions of Chrome, IE11, Edge, Safari, Opera and Firefox. Any problems are entirely your own.