Using Google Analytics' global site tag (gtag.js) to measure Scroll Depth - google-analytics

I have currently implemented Google Analytics on a web property of mine via adding the following Global site tag (gtag.js) on all web pages:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-Y"></script>
<input id="user_id_val" type="hidden" name="user_id" value="{{ user_id }}">
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
var user_id = document.getElementById("user_id_val").value;
if (user_id)
{
gtag('set', {'user_id': user_id}); // Set the user ID using signed-in user_id.
gtag('config', 'UA-XXXXXXXXX-Y');
}
</script>
Note that this snippet has been enriched with user_id to enable session unification.
Next, I need to implement Scroll Depth for my web property.
How do I do that via the Global site tag (gtag.js) I am already using? I cannot find any documentation for the same. Can an industry expert give an illustrative example of how that could be done? And if it cannot be done, it is alright to simply point that out.
Postface:
Normally, Scroll Depth is measured via adding Google Tag Manager to the project. That is well-documented.
So why am I not following the recommended route of adding the Google Tag Manager snippet to measure Scroll Depth? Why am I trying to do it via Global site tag (gtag.js)? Because:
I have read that one can indeed deploy tags via Global site tag (gtag.js) as well. This official doc page explains that this is possible. So what I am attempting makes sense in theory.
I already have the Global site tag (gtag.js) injected all over my site. If I can piggy back on that to enable Scroll Depth measurement, then that is my preferred solution.
My alternative would be to replace the already configured Global site tag (gtag.js) with the Google Tag Manager snippet.
But that introduces the additional headache of how to enable session unification in GTM (another requirement of mine), which I configured with gtag.js. This transition could also break my GA. Or create duplicated effort.
Since that could overall be a messy situation needing a lot of troubleshooting, I am firstly exploring ways of just using the Global site tag (gtag.js) to solve my Scroll Depth measurement issue. Hence this question.

Related

Google Tag Manager equivalent of adding multiple IDs with gtag( 'config' )

I've been working on a migration from Universal Analytics to Google Analytics 4, and am considering switching to Google Tag Manager at the same time. I'm trying to make sure the initial code on the site will work correctly.
Here's what we previously used with Analytics:
<script async src="https://www.googletagmanager.com/gtag/js?id=[analytics id]"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag( 'js', new Date() );
gtag( 'config', '[analytics id]', {"optimize_id":"[optimize id]"} );
gtag( 'config', '[ads id]' ); // this is a different ID than the Analytics one
</script>
The Google Tag Manager looks like this:
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.'+'js?id='+i+dl+'&gtm_auth=[environment auth code]&gtm_preview=[environment id]&gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','[tag manager id]');
</script>
On the Analytics code, I'm able to supply an ID for (universal) Analytics and Google Ads by using the config method. On the new Tag Manager code, there appears to only be one Google Tag Manager ID.
I'm aware that I can add things like Google Analytics 4, Universal Analytics, Google Ads Remarketing, Google Ads Conversion, etc. as distinct Tags with their own ids within Google Tag Manager. But is there an equivalent to this initial config method? Or is that something that Tag Manager takes care of on its own?
GTM takes care of it. Every tag type will load its respective library if it's not yet loaded (it's best to let GTM load its stuff as needed), then execute the config method if it's applicable to the library/tag type and fire events as needed.
GTM will also define dataLayer if it's not defined. It will also hijack the dataLayer from gtag, so no need defining the gtag() function. Basically, pretty much anything you can do with gtag in code is better done through GTM, so if you do tracking properly through GTM, you don't even touch gtag.
dataLayer, in GTM world, becomes a tool of communication between front-end and GTM's logic rather than just direct mindless proxy to GA endpoints, as gtag() offers it.
Useful for GA4 double tracking into different measurement ids, Killan Walsh in Measure slack just uncovered it. You can supply comma-separated measurement ids in the GA4 config tag like so:
Just return comma-separated measurement ids in a string from that var. But this seems like an undocumented, unfinished feature, so use with caution.

Google Analytics does not show Pageviews

I have started to develop my first Typo3-Website.
To track interactions I have included Google Analytics with the following-code in the Setup-Section of the main-template:
page.headerData.9000 = TEXT
page.headerData.9000.value(
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-04738GHDL1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-04738GHDL1', { 'anonymize_ip': true });
</script>
)
With Google Tag Manager-plugin I am able to verify, that a global-site-tag is sent to my G-04738GHDL1 tag
But I am not able to see anything in Google Analytics. Account and property is selected correctly.
Any ideas?
You don't need to anonymize the IP, it is a parameter not foreseen in GA4 since anonymization is always active.
So try replacing this:
gtag('config', 'G-04738GHDL1', { 'anonymize_ip': true });
with this:
gtag('config', 'G-04738GHDL1');
If the TypoScript Object page.headerData.9000 is not overwritten somewhere else in your TypoScript it should work fine. You can check the TypoScript Object Browser in the Template module for that.
Set up correctly, the code should be output in your site's HTML.
From there I would suggest having a look at your browser's inspector tools, checking the console tab for any errors (e.g. regarding JavaScript errors or any CSP violations) and the network tab whether any request towards google are sent.
If you aren't familiar with that, the Google Chrome browser extension Tag Assistant is quite helpful. ;)

Impact of new "gtag.js" AdWords conversion tracking code on existing UA setup

I got an email from Google requesting a change to my AdWords conversion tracking setup. They want me to add new library "gtag.js" and some calls to a "gtag" function.
This seems pretty easy. In my research, though, I've read some things that give me pause, e.g.
"If you have Universal Analytics code on-page and are using any sort of customization to send events, virtual pageviews or other unique data to Analytics, you will likely not want to switch to gtag.js. That would mean updating all on-page customized code to the new gtag syntax. Not sure if you have custom code? Any use of custom dimensions, custom metrics, or events is likely relying on your current implantation of Universal Analytics."
(Source: https://www.bounteous.com/insights/2018/01/30/guide-adwords-conversion-tracking-2018/)
I definitely have Universal Analytics calls in place; I'm not 100% sure what they mean by "on-page" (where else would they be?) but I suspect my stuff qualifies. As for "customization," I do make use of the numbered dimensions (e.g. ga('set', 'dimension4', creditStatusCode) )
Does this really mean I should avoid gtag.js, though? I'm thinking not, but I'd also like to understand what that Bounteous.com post means.
One hunch I came up with is that the post is talking about sites that have actually made their own version of the UA script (i.e. modified analytics.js- I have not done this). Is that it?
You could use Global Site Tag for Google Ads conversion tracking without changing your current GA tracking setup at this point in time (though you would want to look at updating, once you have had a chance to check what needs to be ported over from Universal syntax to Global Site Tag).
If you were to only use gtag.js for google ads it would be similar to the following:
<!-- Global Site Tag (gtag.js) - Google AdWords: GOOGLE_CONVERSION_ID -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-GOOGLE_CONVERSION_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-GOOGLE_CONVERSION_ID');
</script>
If you were to combine the GA and Google Ads tracking the snippet would be along the following line
<script async src="https://www.googletagmanager.com/gtag/js?id=GA-PROPERTY_ID">
</script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA-PROPERTY_ID');
gtag('config', 'AW-GOOGLE_CONVERSION_ID');
</script>
Custom dimensions would need to be mapped in the GA config command
https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dims-mets
You would also need to update any event tracking to the gtag.js syntax, and same would apply to things like ecommerce tracking and so forth.
There is an analytics.js to gtag.js migration guide available
https://developers.google.com/analytics/devguides/collection/gtagjs/migration

The Google Optimize snippet for the container with ID GTM-... is not correctly installed on this page

I'm trying to use Google Optimise with Analytics installed by gtag.js and am getting errors in some parts of the Optimise UI but not others.
Here's what I've done:
Installed Google Analytics following the instructions "Set up Analytics tracking with gtag.js" (and confirmed it's working by using the Real-Time Preview).
Set up Google Analytics following the instructions "Deploy Optimize using Global Site Tag (gtag.js)"
Added the page-hiding snippet.
When I set up an experiment using the Chrome extension, Optimise appears to be running as Google expect - notice that there's no number shown by the exclamation mark icon in the screenshot below (there is if I remove the Optimise code), and clicking it says "no issues detected". (Also, the chrome extension's icon doesn't have any error symbol.)
However, if I then preview either the original or the variant (clicking the "screen" icon in Optimise), I get a javascript alert which says:
The Google Optimize snippet for the container with ID GTM-abcdef is not correctly installed on this page. To preview variants for this experiment, make sure the Google Optimize snippet is installed on any pages you want to test.
(I've replaced my actual container ID by "abcdef" in the above.)
And the Chrome extension icon also shows an error and a similar message when clicked (I've blacked out the experiment name here):
Here's my HTML <head> section (with IDs redacted):
I've compared the script from this with the example in "Deploy Optimize using Global Site Tag (gtag.js)" and they appear identical except that my code contains real IDs:
<head>
<meta charset="UTF-8">
<!-- Page hiding snippet (recommended) -->
<style>.async-hide { opacity: 0 !important} </style>
<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-zyxzyx':true});</script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-abcdef"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-abcdef', { 'optimize_id': 'GTM-zyxzyx'});
</script>
<title></title>
</head>
I've tried this against a site running locally (on Flask's webserver, port 5000) and against a site deployed onto Heroku, and behaviour is the same in both instances.
I've also tried removing the page-hiding snippet code, but that didn't help.
I've also tried actually running the experiment but always saw the original variant even when setting the alternative one to have 100% traffic, so it's not working there. (I only tried this against local site, haven't tried against the Heroku instance.)
It's worth noting that there's this line in the GA code:
function gtag(){dataLayer.push(arguments);}
I've seen it online in that form and with the semi-colon at the end:
function gtag(){dataLayer.push(arguments)};
I've tried both without any effect.
What am I doing wrong here?
I don't know if this is correct, but should the hiding snippet be using the ID UA-abcdef?
If you’re using Google Tag Manager to deploy Optimize, populate the
page-hiding snippet with your Tag Manager container ID, not your
Optimize container ID. Learn more about using Optimize with a
tag-management system (from here: https://support.google.com/optimize/answer/7100284?hl=en)
I'm not sure whether deploying the code this way is classed as deploying Optimize with Google Tag Manager though. What do others think?

Tracking Widgets using google analytics

I have this widget code that i wish to track via GA analytics without changing the code structure. how can i do this using GA event tracking feature.
the widget code is as below:
<script src="http://widgets.unnamed.co.ke/21/index.php?source=mysite" type="text/javascript"></script>
We've added google analytics code to the widget javascript. Note that you need to make some adjustments when the GA code is inside a function in your code. e.g:
var g = window._gaq || (window._gaq = []);
g.push(['some_unique_name._setAccount', 'UA-XXXXXXX-X']);
In addition you have to make sure your GA doesn't interfere with the site's GA. So you need to make sure that the domain (and some other definitions) is set to the same domain as the site's GA definitions. You also should make sure to use your own tracker.

Resources