开发者

Tracking outgoing links with Javascript and PHP

开发者 https://www.devze.com 2022-12-16 09:40 出处:网络
I have tried it using jQuery but it is not wo开发者_运维问答rking. <script> $(\"a\").click(function () {

I have tried it using jQuery but it is not wo开发者_运维问答rking.

<script>
    $("a").click(function () { 
      $.post("http://www.example.com/trackol.php", {result: "click"
  }, "html");
    });
</script>
<a href="http://www.google.com">out</a>


To get the best results you should change two things in your approach

  1. Use onmousedown instead of click - this way you get a few extra milliseconds to complete the tracking request, otherwise the browser might not start the connection to your tracker at all as it is already navigating away from the original page. The downside is that you might get some false-positive counts, since the clicking user might not finish the click (eg. keeps the mousebutton down and moves the cursor away from the link) but overall it's a sacrifice you should be willing to make - considering the better quality of tracking.
  2. Instead of an Ajax call ($.post('...')) use an image pre-fetcher (new Image().src='...'). The fact that the tracker is not an image is not relevant in this case because you don't want to use the resulting "image" anyway, you just want to make a request to the server. Ajax call is a two way connection so it takes a bit more time and might fail if the browser is already navigating away but the image pre-fetcher just sends the request to the server and it doesn't really matter if you get something back or not.

So the solution would be something like this:

<script>
$(document).ready(function() {
    $("a").mousedown(function (){
        new Image().src= "http://www.example.com/trackol.php?result=click";
    });
});
</script>

<a href="http://www.google.com">out</a>


Instead of using JavaScript to call a php tracking script, you could just link to your tracking script directly and have it in turn redirect the response to the ultimate destination, something like this:

<a href="http://www.example.com/trackol.php?dest=http://www.google.com">out</a>

and in the PHP script, after you do your tracking stuff:

...
header("Location: $dest");


As mentioned, the problem is you’re not running the script after the DOM has loaded. You can fix this by wrapping your jQuery script inside $(function() { }, like so:

This works:

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Tracking outgoing links with JavaScript and PHP</title>
 </head>
 <body>
  <p><a href="http://www.google.com/">Test link to Google</a></p>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script>
   $(function() {
    $('a').click(function() {
     $.post('http://www.example.com/trackol.php', { result: 'click' }, 'html');
    });
   });
  </script>
 </body>
</html>

See it in action here: http://jsbin.com/imomo3

0

精彩评论

暂无评论...
验证码 换一张
取 消