How to use google analytic trackEvent?
If you're using async version - and there's generally no reason why you shouldn't then you should always use
_gaq.push(...)
- (where _gaq is just a javascript array, and push()
just adds to the end)
The whole point of this array is that you can store events, whether it's a trackEvent
event or a trackPageView
event before the GA script may have loaded - that's why it's called async tracking. When the script has loaded it processes everything in the array.
If you have javascript on the page that pushes something to this array BEFORE the google script has finished loading then the event will still be tracked as soon as it's loaded. It also works AFTER the script has loaded.
I assume (but haven't verified this) - that once the script is loaded it converts _gaq
to an observable array - or just a direct method call so that once you push anything more to it it can instantly be processed.
I'd recommend using Google Analytics Debugger which is a Chrome plugin published by Google - to see in real time what gets sent. Also this is good for general GA debugging tipe.
Moon
Updated on June 04, 2022Comments
-
Moon almost 2 years
I just jumped into a project that my co-worker used to work. I see the following code.
var _gaq = _gaq || []; _gaq.push(['_setAccount', "my id"]); _gaq.push(['_trackPageview']); _gaq.push(['_trackEvent', 'app', 'DEACTIVATE'])
The problem is, I don't see any user events under google analytics page. I checked Content->Events.
I googled and then found out most people use
pageTracker = _gat._getTracker("id") pageTracker._trackEvent("app","DEACTIVATE");
which one is correct? I like to test it myself first, but the app is already live and GA has a delay of a day. I like to confirm it first.
Update: After digging into it further, I found out that I should use the first approach. However, it still doesn't work unless you pass the value.
var _gaq = _gaq || []; _gaq.push(['_setAccount', "my id"]); _gaq.push(['_trackPageview']); _gaq.push(['_trackEvent', 'app', 'DEACTIVATE',""]) // must pass value even if it's empty