Tracking Widgets using google analytics - 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.

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.

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

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.

Solving configuration mismatch between Google Analytics and Google Optimize?

So I'm using Google Analytics, Google Optimize, and Google Tag Manager. I also feel that I may be losing my mind.
For performance reasons, we don't want to add the google optimize script through GTM. We want to hard-code it. But every time I try that, the installation doesn't work. Specifically, when I click "Run Diagnostics" on the google optimize setup page, I get an error that says
All Analytics tracking code on the page must have the same tracker configuration settings. [...] The following tracker configuration properties do not have the same configurations: alwaysSendReferrer.
So I go into my handy Analytics debugger, find the alwaysSendReferrer property, and note that it's set to true. Great. I edit the config object that i'm passing to the google optimize init script, and I add alwaysSendReferrer: true. So far so good. Except... I get the same error.
I thought maybe something was wrong with our analytics setup, so I got rid of the hardcoded google optimize script and instead included it via the Google Optimize GTM tag -- which, unexpectedly, worked perfectly. I thought "Okay i'll just find the script that GTM is adding and copy/paste it into the codebase" but of course it's minified within an inch of its life, and untangling that javascript from the rest of the tags would be a whole other endeavor.
I have access to a {{Default UA Settings}} variable in GTM, and google's documentation would really like me to just pass that object to the official "Google Optimize" tag in GTM. That works (I've tested it), but as mentioned, we don't want to do that.
If anyone knows what the Google Optimize config object should look like, that would help me massively.
Right now mine looks like this (with identifying details removed)
dataLayer.push(['config', 'UA-12345', {
'optimize_id': 'GTM-55555',
'linker': { 'domains': ['mywebsite.com <http://mywebsite.com>'] },
'alwaysSendReferrer': true
});
I've tried false, "true", 1, and basically everything else I can think of (I'm quite confident that Google Analytics has this property set to true on our site) -- my only guess is that maybe I'm setting the value in the wrong place and google optimize isn't seeing it. Help?
I know the feeling of losing your mind trying to read through Google documentation!
This is the code I use on pages I wish to run Optimize experiments on:
<head>
...
<!-- Google Tag Manager --> <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= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-PRMQXXX');</script> <!-- End Google Tag Manager -->
<!-- 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-KL7XXXX':true});</script>
<!-- Modified Analytics tracking code with Optimize plugin -->
<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', 'UA-99999999-1', 'auto');
ga('require', 'GTM-KL7XXXX');
ga('send', 'pageview');
</script>
...
</head>
Where:
GTM-PRMQXXX is the Google Tag Manager container id
GTM-KL7XXXX is the Google Optimize container id, and
UA-99999999-1 is my Google Analytics id
Note that you need to remove your usual GA script once you add the scripts above.
I hope this helps you!

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

DOXFX using Application Insights end-user user analytics

How can you add Application insights end-user user analytics to DocFx to track the usage of every documentation page?
The Application Insights documentation states you need to insert the JavaScript snippet listed below immediately before the closing tag, but I'm not sure if this is possible in DocFx or the best way to accomplish.
Would you need a postprocessor, or could you use a custom template?
<!--
To collect end-user usage analytics about your application,
insert the following script into each page you want to track.
Place this code immediately before the closing </head> tag,
and before any other scripts. Your first data will appear
automatically in just a few seconds.
-->
<script type="text/javascript">
var appInsights=window.appInsights||function(config){
function i(config){t[config]=function(){var
i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o="script",s="AuthenticatedUserContext",h="start",c="stop",l="Track",a=l+"Event",v=l+"Page",y=u.createElement(o),r,f;y.src=config.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(y);try{t.cookie=u.cookie}catch(p){}for(t.queue=[],t.version="1.0",r=["Event","Exception","Metric","PageView","Trace","Dependency"];r.length;)i("track"+r.pop());return i("set"+s),i("clear"+s),i(h+a),i(c+a),i(h+v),i(c+v),i("flush"),config.disableExceptionTracking||(r="onerror",i("_"+r),f=e[r],e[r]=function(config,i,u,e,o){var s=f&&f(config,i,u,e,o);return s!==!0&&t["_"+r](config,i,u,e,o),s}),t
}({
instrumentationKey:"###-###-###-##"
});
window.appInsights=appInsights;
appInsights.trackPageView();
</script>
No PostProcessor is needed. You can achieve this by customizing the template. More information can be found in official tutorial or this question. You can add your code in partials/head.tmpl.partial. It will affect all the generated page.

Resources