Nir
Nir

Reputation: 25369

JS : How to track click on links without losing the back button

I have a js widget which is embedded in random sites.

When a user clicks a link I want to report it to my server.

To call my server I create a tag dynamically with src containing the parames reported to the server.

If I do it on onclick event and return true from the onclick, the server probably will not get the call because the browser changes the page (is this correct?).

If I do it on onclick and return false then use redirect after the call to the server is returned, I lose the back button functionality because browsers like IE do not support the back button after redirect.

Any idea of how to do this in a robust way?

Upvotes: 0

Views: 1768

Answers (1)

Jan Jongboom
Jan Jongboom

Reputation: 27342

There is no problem. If you add an onclick handler to the <a> elements that sends an AJAX POST to the server (registering the click), this will arrive at the server, the page will still move on to the clicked link, and the back button will work as expected.

Example in jQuery:

$('a').live('click', function () {
     $.post('/registerclick/', { data: $(this).attr('src') }, function () {});
});

The reason this works, is because the client/server model in HTML specifies that when a request is sent to the server, it cannot be cancelled. Therefore the following applies:

  1. Event handler goes off, and a request to the server is sent
  2. User gets redirected by default browser behavior to the page in the href attribute
  3. Server gets the request, even tho the user is at a whole different page

The browser isn't aware of the 3rd step; but that doesn't matter for the server.

Upvotes: 4

Related Questions