Track outgoing links with Javascript


First step. Creating tracking code

This idea came about from search engines ability of tracking users activity on their pages. They are tracking users clicks and using this information in further investigations.

For example, each outgoing link in MSN search results looks like
<a href="" gping="/GLinkPing.aspx?/_1_9SE/">Site</a>

and code that is tracking users can be found in included JS file.
if(g(e,c)){a=new Image;a.src=c.attributes["gping"].value;return true}

It's not difficult to understand that we can attach onclick event handler to any link and use creating of new image to send some data to remote script. Take a look at this code:
function track (link)
      new Image().src = ''+ link.href;
<a href="" onclick="track(this)">Link</a>


Second step. Many links, many problems

We wrote simple code that can be easily inserted to any webpage. We can add onclick handler to any link and track it. But what shall we do, if we have 100 links on a page, or even 1000? (I saw pages with more than 10 000 outgoing links on them).

Just imagine, if it is static page, we should manually change each link. Even if links are generating with PHP script or some other dynamic way - don't forget about page size.

But this problem can be solved.
Get acquainted - Behavior (
Author of this script is Ben Nolan and it is really useful thing.

Let me use quote from Ben's website:


Behaviour lets you use CSS selectors to specify elements to add javascript events to. This means that instead of writing:

    <a onclick="this.parentNode.removeChild(this)" href="#">
      Click me to delete me

You can use:

<ul id="example"><li><a href="/someurl">Click me to delete me</a></li></ul>


You can learn more about this script from his webpage, but there is no need to do it right now. Let's finish with this article :)

All that we shall do - put our tracking code directly to the end of Ben's script. Tracking code:
var myrules =
    'a' : function(el)
      el.onclick = function()
        new Image().src = ''+ this.href;


Final step. Results and full source code

You can download full javascript code here: track.js (click right button and choose save object as)

Now you need to write PHP (Perl, so on) script that can save information about clicks (to file, database, or simply sending e-mail to you).

For example, you created track_click.php and put it to Change to in track.js. (line 261, near end of file).

Upload this file to website.

Insert this code in head section of your html page and start tracking all visitors immediately.
<script type="text/javascript" src=""></script>
Don't forget to change to your page address.

If you are experiencing problems with PHP, you can create track_click.php with this code inside: <?php mail('', 'subject', $_REQUEST['href']);?>


Any questions?
You can write a short message for me and i will give you answer right here after some time.