We help IT Professionals succeed at work.

Onclick web beacon request

PlumInternet asked

We have a button which we would like to track with a hardcoded Google Analytics web beacon. We have the hard coded web beacon we just need to know what we would need to add to the href tag to make sure that the web beacon fired.

Ie <a href="page.html" onClick ??????<web beacon>>

Watch Question

Top Expert 2011
What is the code for the Google beacon you want to fire?  Depending on what it is, that may change my suggestion.

Kinda clunky, but one method I've solved this problem with in the past was to hijack the <a href> so that it went through a handling page which fires the beacon then redirected the user to the location requested in the <a href>.  

Through testing the resulting analytics, I found this method to be more reliable than creating an HTML element on the fly and then redirecting them (e.g., adding the beacon to the webpage before taking the user to their destination)... about 40% of the time, the user would redirect before the beacon completed.

In this example, the "processClick" function merely sends the user back to the current page.  For your case you would want to change "window.location.href = window.location.href+ "?goto=" + obj.href;" to something like "window.location.href = "WebBeaconHandlerPageGoesHere?goto=" + obj.href;"
<script type="text/javascript"> 
function processclick(obj)
window.location.href = window.location.href+ "?goto=" + obj.href;
return false

<a href="http://www.yahoo.com" onclick="processclick(this);">Yahoo Website</a>
<a href="http://www.wiki.com" onclick="processclick(this);">Wiki Website</a>

Open in new window

Your WebBeaconHandlerPageGoesHere would include the code for the web beacon and you could use JavaScript's window.onload to take the user to their destination:
window.onload = function ()
  //Javascript code goes here.  You can get the target URL from the querystring

Open in new window

If you are using jQuery, some of this could be simplified, but the approach would still be about the same (I would suggest using .load() to load the beacon, which resides in a separate text file on your server into a DIV that exists somewhere on the page and the "success" function of the load would be to redirect the user to the href location.  You would also "prevent default" of the affected hrefs.)