One of the best features for a developer I’ve found so far in my hour of playing around is the ability to have a callback method executed after you’ve sent some data.

The prime case would be when you would track a link as an event. You would use a setTimeout to trigger the clicked link after you’d hoped the event had been sent to Google. No more! You can now use the following piece of javascript utilising the hitCallback function:

Matthias

March 17, 2014 at 1:50 am

Hi Dom, thanks for the great summary. I have a question too.

For a client site we are trying to register a virtual pageview or event with a click to an outgoing link just like in your example. However, we can’t embed the actual document location in the hit callback function – the developers have told me that it’s not possible in our case because of the way their setup works. The URL isn’t actually read from the HTML.

The events I can see in Google Analytics have remained exactly as before the hit callback had been implemented. My question now, do you think the hit callback function can work without an argument? Will the code wait for the hit callback anyway before redirecting to the new URL?

Will the code wait for the hitCallback before redirecting to the new URL? Without putting any sort of variable or function to execute inside the hitCallback function, or more to the point, prevent your code / HTML that is directing the browser to go to the new URL, then the hitCallback function will have no effect.

Ideally, depending on your setup, you first need to prevent the action of address change from firing.

If it’s an anchor tag, something simple like:

$("a").on("click", function (e), {
e.preventDefault();
});

Since you have stipulated you can’t get the URL inside the hitCallback function, you could maybe have a variable that sits outside the function that is set to false, and inside the hitCallback function, set it to true. You could then have a function that checks this variable every 200ms.

Matthias

March 21, 2014 at 12:02 am

Hi Dom, thank you so much for your reply and the awesome suggested solution! We will test your approach and I will let you know how it goes. If need be I will check with the devs to explain their implementation a bit more. Many thanks!