Google Analytics Event Tracking - Not working for a download link - google-analytics

I just finished working on a plugin for Sketch and I created a simple landing page for users to download the plugin. I want to use Google Analytics event tracking to track the downloads, but the event tracking is not working and I can't seem to figure out why.
Here is what the link looks like:
Download
Does anyone see what I'm doing wrong? Do I need to add any other code anywhere else besides the onclick attribute?

My bet is that you're facing what we call a race condition: the moment the user clicks the link, the browser initiates a page change, thus GA is interrupted before it's had a chance to send the event.
2 options
Open link in new tab: add target="_blank" to your links so they open in a new tab and don't interrupt GA in the current tab.
Prevent Default + Hitcallback: you can use a custom function for onClick that will prevent the link from opening by default (return false;), trigger the GA event, and use GA's hitCallback to trigger the page change programatically.
For option 2 there are different ways of doing it (since it's custom code). Here is an example from Google:
https://support.google.com/analytics/answer/1136920?hl=en
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
You'll also need to add (or modify) the onclick attribute to your links. Use this example as a model for your own links:
Check out example.com

Related

Google Analytics - Events data not reflecting

In my website we have a banner which on clicking directs the user to our client's website. In order to track the number of people clicking the banner we decided to make use of the google analytics events component. I added the JS provided by them just below my Google analytics script.
var captureOutboundLink = function(url) { ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitCallback': function(){document.location = url;} }); }
Then in the place of the banner I called the function
<a href="https://example.com/pg/" onclick="return captureOutboundLink('https://example.com/pg/');">
<img src="https://www.moreexample.com/admin/banner/mascot.jpg" alt="macott2022" title="macott2022" class="img-res innerbann" />​
But the google analytics events tab is still not tracking. I tried clicking the Banner few times but it shows no signs of activity. Does it take time to reflect ?
​
yes, events report might need some time to process the data. you can use "events" section of real-time report instead.
moreover you might use Tag assistant or other GA debugging tool to make sure that your event data being sent.

Tracking user link clicks with google analytics

I have created an affiliate marketing website. Here users will register on my website and shop, however the shopping link will be of amazon.
I need to know how to set up Google Analytics so that it can track which registered user has clicked an affiliate link on my website.
For example I have this amazon link
https://www.amazon.in/BassHeads-225-Super-Extra-Headphones/dp/B01M9C51T9/ref=sr_1_1?_encoding=UTF8&pf_rd_i=desktop&pf_rd_m=A1VBAL9TL5WCBF&pf_rd_p=14ffe21a-e5a2-45c9-a9c0-91f47b082bbc&pf_rd_r=94G5Y8CM93G8M5Y2SNS3&pf_rd_t=36701&qid=1554008093&s=gateway&smid=A14CZOWI0VEHLG&sr=8-1
I know I'm supposed to put an onClick event on there somewhere but I don't have any idea how it links to Google Analytics? I am using Google Tag Manager
Is this the correct Onclick code:
onClick="_gaq.push(['_trackEvent', 'Link', 'Click', 'Banner Advert1']);"
If not what do I need to add to track the registered user?
I have many links to external sites on my website; an example link looks like this:
<a id="Buy" data-itemDescription="(a description)" data-itemValue="2.80" href=http://externalsite?id=6789>
The key things here are the extra attributes before the href: id (used to identify the specific event that occurs when the link is clicked, i.e. in this case a Buy event) and the data-itemDescription and data-itemValue metadata (used in constructing the event label etc.)
The relevant GTM artefacts are as follows:
Trigger:
Buy: Click - Just Links when Click Id contains Buy
User-defined variables (custom Javascript):
ItemDescription:
function() {
return {{Click Element}}.getAttribute("data-itemDescription");
}
ItemValue:
function() {
return {{Click Element}}.getAttribute("data-itemValue");
}
ItemValueFloat (100 multiplier used because GA didn't like my decimal places - I then divide by 100 at reporting time to get the right answer):
function() {
return parseFloat({{ItemValue}})*100;
}
Tag BuyClicked is an Event triggered by the Buy trigger as above, with:
Category = Purchase Tracking
Action = Purchase {{ItemDescription}}
Label = {{Page Path}} : {{Click URL}}
Value = {{ItemValueFloat}}
I also have Non-Interaction Hit set True.
The BuyClicked event is then collected by GA, and reportable on from e.g. Google Data Studio, without my having to do anything further.
If you can't add an id or metadata, you could undoubtedly do the same sort of thing more painfully by handling all clicks through a single trigger and then parsing the Click URL via custom Javascript to get granular Categories, Actions, Labels.

Cross domain tracking on right click

Is there a way to pass GA cookies for cross domain tracking when user uses right click (instead of a left click) to hop domains?
It would seem that reliance is on autoLink, which decorates links automatically on left click and does not directly provide for alternative events.
Since I'm working on assumptions I'm not providing complete solutions.
Per autoLink in GA's analytics.js devguide:
// Loads the Linker plugin
ga('require', 'linker');
// Instructs the Linker plugin to automatically add linker parameters
// to all links and forms pointing to the domain "destination.com".
ga('linker:autoLink', ['destination.com'], false, true);
This will also operate on oncontextmenu so if the visitor right-clicks and selects "Open in new tab", the link is still decorated and will have the data appended.
Where decoration is required on other events, autoLinking needs to be extended by manually adding linker parameters using:
ga('linker:decorate', destinationLink);
Such a function call decorates a link based on the domains listed in the 'linker:autoLink` array above. It can be adapted to apply to all cross-domain links.
Assuming the context menu needs to be disabled:
From Andy E's answer
destinationLink.oncontextmenu = function ()
{
ga('linker:decorate', destinationLink);
console.log(destinationLink.href);
document.location = destinationLink.href;
return false;
}
That will decorate the link on right click and direct the browser to the decorated URL.
If the context menu is already disabled, abbreviating Andy E's code:
destinationLink.addEventListener('mousedown', function (e) {
console.log('mousedown', e);
if (3 == e.which) { // is it a right click
ga('linker:decorate', destinationLink)
document.location = destinationLink.href;
}
})
Note that decoration must occur as soon as possible before the visitor clicks since the parameters expire after 2 minutes.
Analytics Ninja, adapt your code to your specific requirements and if you run into further issues, please follow Philip Walton's advice

Google Tag Manager - How to avoid data loss

I am using Google Tag Manager to register events with Google Analytic. At one plance I am changing url on the changeof a dropdown. I want to track the same event on Google Analytics. I am worried what would happen if page is changed before event is registered with GA. Could you please let me know if there is a feature in GTM that can ensure that page is not changed before event is registered with GA.
Here is the code that will execute on the change of the dropdown
var targetCityChangedEventName = "TargetCityChanged";
$("#location", topHeader).bind({
"change": function(ev, obj) {
dataLayer.push({event : targetCityChangedEventName });
var url = "http://" + window.location.host + "/" + $(this).val();
window.location = url;
}
});
If you are using ga.js (asynchronous Analytics) you can set an hit callback (a macro that returns a function) in the tag template under "advanced configuration and do the redirect there (possibly you'd need a separate analytics tag just the change event).
If you use Universal Analytics there was a discussion at the Tag Manager Google Group a while ago where Googles Brian Kuhn suggested the following way ( I have not tested this):
In the meantime, have you tried this?
dataLayer.push({callback:
function() {
alert(123);
});
Then, create a dataLayer macro that reads the "callback" key. Then,
use that macro as the value of a "fields to set" pair on your UA tag,
under the field name "hitCallback".
Instead of the alert you'd do the redirect.
In case that's not clear, a hit callback is a function that can be passed to the tracking calls and is executed after the tracking call has executed.
I was able to resolve the same issue by simply inserting a delay. The dataLayer.push doesn't need to return anything, so a 100 millisecond delay is sufficient in 99% of the cases for the dataLayer.push to be executed.
dataLayer.push({ ... });
setTimeout( function(){ window.location = ...; }, 100 );
Note that the GTM preview/debug mode gives false positives - you must make sure that your tags are actually being fired, in my case my event was for a virtual pageview and I could see the results in RealTime Analytics. Without the delay, I could see that the tag was not being fired.

Google Analytics events fail to show up

I'm trying to get Google Analytics working on my blog, but the events are failing to show up in my account.
Part of the issue is that I'm using the new async code, but most of the documentation relates to the older synchronous version. I've read a bunch of SO and blog posts but can't quite see what I'm doing wrong.
One mentions that you have to "activate" event tracking in your site's profile, but I can't find where I might do that.
I originally put my Google Analytics code in an external file called ga.events.js, which is still linked from my site. I attached the events from a jQuery loaded event:
$(function () {
$('.rss').click(function() {
trackEvent("engagement", "rss subscribe", "rss subscription link clicks");
});
function trackEvent(category, action, label) {
_gaq.push(['_trackEvent', category, action, label]);
}
});
But I found a post that said you can't link in an external file for Google Analytics, so I also tried the old fashioned onclick approach:
email list
I put the _target="blank" attribute in case the request wasn't completing before the user navigated away from the page.
Executing the code in the Chrome console on my site returns a 0, when I was expecting a boolean value:
_gaq.push(['_trackEvent', 'Engagement', 'click', 'RSS subscription link'])
I've waited 24 hours after each of these tests to see if the event tracking wasn't real time.
What else should I try? Any obvious mistakes?
Figured it out. I had onclick instead of onClick with a capital C. Wait, JavaScript is a case sensitive language? Who knew?
I also had the syntax of the GA call incorrect.
Here's what my working code looks like:
email list
And here's a version that works using jQuery to attach the click handlers:
$(function () {
$('.rss').click(function() {
trackEvent('Engagement', 'Sidebar link click', 'RSS feed subscription');
});
function trackEvent(category, action, label) {
_gaq.push(['_trackEvent', category, action, label,, false]);
}
});

Resources