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]);
}
});
Related
I would like to track beforeunload event on SPA website, as I want to send data via GTM to datalayer. I want to track video watch time (HTML5 player) and send the data right before a user leaves the current page either to another one on the same website or completely different.
Is there a way to have this done via GTM custom HTML?
Assuming that you have a way to capture the video time in a variable, you can send that information to Google Analytics using an event listener for the beforeunload event. I’m doing that on one of my webpages to get an idea of how long users have the page open.
Here’s the code I’m using:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
// Disable tracking if the opt-out cookie exists
if (document.cookie.indexOf("ga-disable-GA_MEASUREMENT_ID=true") > -1) {
window["ga-disable-GA_MEASUREMENT_ID"] = true;
}
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag("js", new Date());
gtag("config", "GA_MEASUREMENT_ID", { "anonymize_ip": true, "cookie_flags": "SameSite=None;Secure" });
</script>
<script>
window.addEventListener("beforeunload", function (e) {
gtag('event', 'Time_Spent', {
'event_category': 'Time_on_page',
'event_label': e.timeStamp.toString,
'value': 1,
'transport_type': 'beacon'
});
delete e.returnValue;
});
</script>
The first section is in the head and the second section is at the end of the body.
I put the event.timeStamp value in the event_label; you could put your video time, formatted however you like into that field as well.
I’m not sure I need the optional value field, but I have it.
The transport_type beacon tells Google to transmit the data asynchronously when the User Agent has an opportunity to do so, without delaying unload or the next navigation.
To see how long people have been spending with my page open, I go to:
Google Analytics -> Behavior -> Events -> Overview
I click on the event category (Time_on_page in my case), and then click on Event Label to get a listing of all of the values.
When navigating around in my SPA, I'm firing VirtualPageView events, but this is what the Google Analytics debugger spits out:
It seems to be recreating the Google Analytics tag over and over. I'm not a GA expert, but from what I read, this is really bad for proper analysis. I think it has something to do with restarting the user session over and over?
The Google Tag Assistant seems to think the GTM itself is being recreated:
Things seem fine in the GTM preview console:
To emphasize my concern: The GA tag/tracker seems to be repeatedly recreated. Am I right? If so, how do I fix it?
For a reference, here's what I got configured in GTM:
The key functions that handle GTM events in my app are as follows:
const sendEvent = ({event, eventCategory, eventAction, eventLabel}: GtmEvent): void =>
send({
event,
eventCategory,
eventAction,
eventLabel,
nonInteraction: false
});
const sendVirtualPageView = (data: { url: string, title: string }): void =>
send({
event: <'VirtualPageView'>'VirtualPageView',
virtualPageURL: data.url,
virtualPageTitle: data.title,
});
const send = (data: GtmEvent | VirtualPageView): void =>
window.gtm.push(data);
GTM creates a new instance of the tracker object with a random name for every hit. While I do not have any official information I assume that is done to avoid hit scoped custom dimensions and other settings being automatically propagated to all GA tags, if you want them to or not (i.e. you might want to send different information for pageview tags and event tags). Also this avoids trackers overwriting each other if you track to more than one GA account.
If you want to have settings shared between GA tags you can now use the settings variable, and set anything specific to a tag directly in the tag settings.
So what you are seeing in the debugger just means that GTM is working as expected. as for Tag Assistant, while this is a potentially useful tool it gives an awful lot of false alarms, so use it with some caution.
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
I have a banner on my sites home page, It has multiple links and the html code is written within tag and does not contains any anchor links, instead it has a href link only.
My IT heads says its not possible to embedd a onclick event tracking code to track all the links.
Please let me know how will i track this?
A pure unobtrusive javascript solution (derived from Googles example, working but not necessarily the most complete or beatiful code) :
function addListener(element, type, callback) {
if (element.addEventListener) element.addEventListener(type, callback);
else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
links = document.getElementsByTagName('a');
for(i=0,cnt=links.length;i<cnt;i++) {
addListener(links[i], 'click', function() {
ga('send', 'event', 'button', 'click', 'nav-buttons');
});
}
If you put that in an external js file or an inline script it will "decorate" all links in the page (you would need a more specific selector instead of "all links") with a click event that fire google event tracking when somebody clicks the link. No embedded click code in the link tags necessary (that's bad practice in any case).
If you are already using jQuery (since that's probably the most popular javascript library) you can simply do
$( "a" ).click(function() {
ga('send', 'event', 'button', 'click', 'nav-buttons');
});
(again, choose a more specific selecor).
Both examples assume Universal Analytics, for classic you'd need to change the event tracking code (see DalmTos answer for examples).
The following examples will depend on if you are running classic VS universal analytics.
For Classic Analtyics look for ga.js in your tracking code:
Play
For Universal Analytics look for Analtyics.js in your tracking code:
Play
I don't see any reason why you wouldn't be able to track it in your banner.
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.