views:

242

answers:

2

Hi,

I'm trying to make a link tracking script. It should work like Google Analytics only it should make posts to our own server. I'm using jQuery for this. The code i have written so far is the following:

jQuery(document).ready(function() {

var opts;

jQuery.fn.trackAllLinks = function(settings) {
 settings = jQuery.extend({}, jQuery.fn.trackAllLinks.defaults, settings);
 opts = settings;

 function track() {
  href = jQuery(this).attr('href');
  var trackImage = new Image(1, 1);
  trackImage.src = opts.linkredirector + '?eurl=' + jQuery.URLEncode(href) + '&rnd=' + new Date().getTime() + '&title=trackerimage.gif';
  trackImage.onload = function() { 
   trackImage.onload = null; 
   doNothing(); 
  }
  delay(300);
  return true;
 };

 function delay(mseconds) {
  var currentTime = new Date();
  var endTime = currentTime.getTime() + mseconds;
  while (currentTime.getTime() < endTime) {
   currentTime = new Date();
  }
 }

 function doNothing() { 
 }

 if(jQuery(this).is("a")) {
  jQuery(this).click(track);
 }

 jQuery(this).find("a").click(track);

};

jQuery.fn.trackAllLinks.defaults = {
 linkredirector : '__url_to_post_on__'
};

});

It works fine in all browsers except Safari. When i'm using a mailto link or an anchor it works but when i'm linking to another page it doesn't work. I have been testing a lot of different implementations and i can't get it to work. Any of you have an idea what i'm missing? I have tried to understand how Google Analytics works and as far as i can see it does the same. When i use WireShark to monitor my network i see that the image of Google is being requested but that my image isn't.

greets, Daan

A: 

Try increasing the delay to something huge to see if Safari is just taking a tiny bit longer than your delay - that's my guess at this issue.

Sohnee
i forgot to tell this, but already tried setting it a bit longer .. until a few seconds and nothing seems to work :/ it's as if Safari is waiting for the javascript to be done before it will request the image. I also just saw that when i'm combining it with GA and my request is done before GA it will be executed.
Daan Poron
How about cancelling the default action, but setting it to occur later. i.e. cancel the navigation, but set a timeout to navigate after a short delay?
Sohnee
A: 

This is random, but you might try adding a randomized parameter in the query string (both the name & value), like:

Math.random(0, 1000) + '=' + Math.random(0, 1000)

I've had to do that in the past to get Safari to register a dynamically loaded resource. (I see you have &rnd= already, but maybe try randomizing the name, too?)

JKS