Tuesday, July 23, 2013

Tracking events in Google Analytics before the HTML Form be submitted

I faced a problem in Google Analytics that finally resolved. Thanks to the awesome Stackoverflow.com. This is the original thread.

Google Analytics was not tracking my event of downloading document generated dynamically.
When the user click on the "Export to Word" button, the event should be tracked, and after it, the download start. Google Analytics tracks events in asynchronous way (of course) so, when the form was submitted, the event was not tracked because there is not enough time to do it.

The JSF form with problem:
<h:form id="frmButtons">
<h:commandButton id="btnExportWord" class="red" value="#{i18n.exportWord}"
style="padding:10px 20px;" action="#{decodeBean.exportToWord}"/>
</h:form>
view raw form.xhtml hosted with ❤ by GitHub
After trying some proposals of the guys helped me, I mixed the solutions and got this with jQuery:
$("#frmButtons\\:btnExportWord").click(function (e) {
//track the event
_gaq.push(['_trackEvent', 'Decode', 'Decode copying', 'Export to Word']);
var button = $(this);
//create a delay and call the same click
if (button.data('tracked') != 'true') {
e.preventDefault(); //consume event if not tracked yet
setTimeout( function(){
button.data('tracked', 'true');
button.click(); //call again the submit
}, 300);//enough time to track the event
} else {
//reset the flag
button.data('tracked', 'false');
//let form being submited once the event is already tracked
}
});
view raw TrackEvent.js hosted with ❤ by GitHub


I did not like the code, but is the only that worked for me in any browser  (Safari, Chrome, Firefox and Opera).

My solution is done in JSF 2, so, I need to submit the original event, once there are some hidden information in the html generated by the framework that I need to respect to get the right events in the server side. Just submitting the form in javascript, per example, will not call my desired methods on server side, that's why I need to call the event recursively.

No comments:

Post a Comment