I've set up Google Analytics on my site, now there are some external links that I have to track.
According to the official Google Analytics documentation, you just have to add a onclick EventListener on your element. Like this:
<a href="#" onclick="ga('send', 'event', 'EventCategoryName', 'EventName');">click me</a>
But it does not seem to work on my site. I disabled all ad-blockers, etc. If I check the network tab in my developer tools, there is no request once I click the link. I'm working with the latest google analytics.js
Can anybody give me a hint?
I found out, that I was using the gtag.js
version of Google Analytics, with the following tracking code:
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID');
</script>
As described in the gtag.js documentation. You should use the following snippet to track a event:
gtag('event', 'login');
Unfortunately it didn't work.
My temporary solution: I went back to the analytics.js version, using the following snippet:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'GA_TRACKING_ID', 'auto');
ga('send', 'pageview');
</script>
Now I'm able to successfully track if a user clicks an external link (or what ever action I want to track):
ga('send', 'event', 'EventCategoryName', 'EventName');