Keeping track of visitor's clicks

Posted on April 10th 2021 in HTML by Pim Debaere.

Keeping track of visitor's clicks

"How many clicks will this hyperlink get on my website?" A simple question like this should actually get a simple answer, don't you think? The easiest way to do this is to leverage existing platforms, of which Google Analytics is perhaps the best known. But even they fail to keep track of how many people click an off-site hyperlink.

Server-side scripting

Of course, you can handle this yourself by not calling the URL directly, but calling a referring page instead. Here you can save the data you want to keep, for example the number of clicks. In turn, this page will then redirect the visitor to the final destination.

Note that this is a bit cumbersome and requires access to the server to create such pages.

Client-side scripting

With JavaScript you also get a lot further, but here too the solution is not so trivial. First and foremost, you need to prevent the hyperlink's default action (opening the URL), call up another page from code through some call that stores the data, and then redirect the visitor to the actual URL.

Ping!

We have already mentioned three possibilities, but none seem to be ideal. Fortunately, there is a simple way: in HTML with the standard attribute ping. This is an attribute on an anchor (hyperlink, <a>) that causes an extra URL to be called as a PING request.

1
2
<a href="https://pimaxplus.com/blog"
   ping="https://pimaxplus.com/analytics/?url=blog">Blog</a>
Fig. 1 – Example of the ping attribute.

In the example above, the user is redirected to my blog, but at the same time a PING request is sent to an analytics page that can keep track of which URL is being called. This does not have to be a page on your own website, or vice versa, so you can track and analyze every click.

So is the ping attribute always the best solution? No, not necessarily. This attribute only works on hyperlink clicks, so not for every event. If you also want to accommodate other events in your web app, you will be forced to fall back on JavaScript.