Google Universal analytics cross domain tracking - google-analytics

I am trying to track cross-domain calls using Universal Analytics, I've copy-pasted the code right from the google documentation and for some reason it is not decorating the external link with the expected parameter (like _ga=1.182119591.1441315536.1362115890410).
Following there is the exact code we tried:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript" >
var UAAccount = 'UA-0000000-0';
var UATrackerName = 'pageTracker';
(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','http://www.google-analytics.com/analytics.js','ga');
ga('create', UAAccount, 'auto', {'allowLinker': true });
ga( UATrackerName + '.send', 'pageview');
function decorateMe(event) {
event = event || window.event; // Cross browser hoops.
var target = event.target || event.srcElement;
if (target && target.href) { // Ensure this is a link.
ga('linker:decorate', target);
}
}
// Cross browser way to listen for events.
function addListener(element, type, callback) {
if (element.addEventListener) element.addEventListener(type, callback);
else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
$( document ).ready(function() {
var linker;
var myLink = document.getElementById('pippo'); // Add event listeners to link.
addListener(myLink, 'mousedown', decorateMe);
addListener(myLink, 'keydown', decorateMe);
});
</script>
</head>
<body>
anchor
</body>
</html>
I've tried to use the dynamic linker instead of decorating each link:
ga('require', 'linker');
ga('linker:autoLink', ['goo.gl']);
but without success: the external link will be without the _ga parameter.

For some reason you are giving the tracker a name of 'pageTracker', but you are not using that name when calling the object methods, including create and linker methods:
ga('create', 'UA-XXX-Y', {name: 'pageTracker'});
ga('pageTracker.linker' ...);
ga('pageTracker.require' ...);

Related

google analytics traffic increase drastically when using setTimeout() function for GTM, GA, GTAG & FB scripts

I am using this code to load the tracking scripts 3000 ms after page load to optimize page speed.
I have checked using the chrome extension tag assistance legacy by google plugin and no major issues are recorded other than Same web property ID is tracked twice on google analytics
<body onload="loadtracking()">
<script>
function loadtracking(){
loadgtm();
loadfbpixel();
loadga();
loadgtag();
}
</script>
<script>
function loadgtm() {
setTimeout(function(){
(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-xxxxx');
// window.dataLayer = window.dataLayer || [];
}, 3000);
return true;
}
</script>
<script>
function loadfbpixel(){
setTimeout(function(){
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;t.defer=true;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', 'xxxxx');
fbq('init', 'xxxxx');
fbq('track', 'PageView');
fbq('track', 'CompleteRegistration', {
content_name: 'Sign up',
content_category: 'xxxxxx'
});
}, 3000);
}
</script>
<script>
function loadga(){
setTimeout(function(){
(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', 'xxxxx', 'auto');
ga('send', 'pageview');
ga('send', 'event', 'xxxxx', 'xxxxx', 'xxxxx');
}, 3000);
}
</script>
<script>
function loadgtag(){
setTimeout(function(){
scriptgtag = document.createElement('script');
scriptgtag.src = "https://www.googletagmanager.com/gtag/js?id=xxxxx";
scriptgtag.async = true;
document.body.append(scriptgtag)
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'xxxxx');
gtag('event', 'conversion', {'send_to': 'xxxx'});
}, 3000);
return true;
}
</script>
But the traffic on GA increased drastically once I implemented this code by x 15
increase in traffic
I cant seem to figure out the issue.
You're loading Google Analytics to the page more than once (potentially even more if you're also loading it through Google Tag Manager) and it's firing a pageview for each of those loads. Let's step through each of your <script> blocks.
<script>
function loadgtm() {
setTimeout(function(){
(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-xxxxx');
// window.dataLayer = window.dataLayer || [];
}, 3000);
return true;
}
</script>
This starts by loading GTM to the page. In order that its own triggers properly work, it's typically advised that this run in the <head> tags of your page. It loads asynchronously and non-blocking so running it on your page would hardly impact perceived page speed.
If you have a GA tag installed within GTM, this accounts for at least one pageview.
<script>
function loadfbpixel(){
setTimeout(function(){
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;t.defer=true;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', 'xxxxx');
fbq('init', 'xxxxx');
fbq('track', 'PageView');
fbq('track', 'CompleteRegistration', {
content_name: 'Sign up',
content_category: 'xxxxxx'
});
}, 3000);
}
</script>
This simply loads the Facebook pixel, so we'll skip over it, except to say that I would instead advise loading this within GTM triggered at pageview.
<script>
function loadga(){
setTimeout(function(){
(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', 'xxxxx', 'auto');
ga('send', 'pageview');
ga('send', 'event', 'xxxxx', 'xxxxx', 'xxxxx');
}, 3000);
}
</script>
That brings us to the first of your explicit Google Analytics installs. Assuming you're not running something like this from within GTM, this sends a pageview and your event after your 3000ms timeout. Again, from an interest of minimizing page speed impact, you should use the built-in Google Analytics tag within GTM and augment it with the event you wish you fire (though I advise making the switch to GA4 before the collection cut-off next year).
<script>
function loadgtag(){
setTimeout(function(){
scriptgtag = document.createElement('script');
scriptgtag.src = "https://www.googletagmanager.com/gtag/js?id=xxxxx";
scriptgtag.async = true;
document.body.append(scriptgtag)
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'xxxxx');
gtag('event', 'conversion', {'send_to': 'xxxx'});
}, 3000);
return true;
}
</script>
This brings us to the Gtag loader, which is really just a means of loading a small GTM instance to your page that bundles the Google Analytics tag. This would account for your second pageview in GA. Since you have GTM installed to the page, you shouldn't be using this loader at all and should instead opt for the built-in GA tag within GTM.
Best case, you're double-counting pageviews. Worst case, you're counting 2x + however many GA pageview tags you're firing off within GTM.
My advice:
Install the Google Tag Manager function without the timeout as high within the <head> tags as you can as provided by their installation instructions.
Install your Facebook tag as an HTML script (drop your timeout function) and trigger to execute at Page View.
Install the built-in "Google Analytics: Universal Analytics" tag, configure accordingly and trigger to run at Page View.
Install the built-in "Google Analytics: GA4 Configuration" tag, configure accordingly and trigger to run at Page View. This will be used by other GA4 tags for the base configuration, but also fires a pageview event without need for a second event-specific tag for the same.

Analytics pageview/ event code is result in stats

I am trying to get statistics about sign ups on my website.
The analytics code is in the header:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=...."></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '....');
</script>
Then I have a form and sending it (with a page reload, not ajax) and in the success snippet in razor I placed the ga code:
#if (success)
{
<script type="text/javascript">
ga('send', 'event', 'Supplier sign up', 'click', '/signup/success');
</script>
<p>success message</p>
}
The success message appears and I can see the script in the page inspect but I don't get any stats in Google Analytics.
Am I missing something? In the past (a few years ago) I was using a similar code and it worked. Has anything changed recently? Do I need to enable something in the Analytics or my code is wrong?
I am following the documentation:
https://developers.google.com/analytics/devguides/collection/analyticsjs/events
https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
The implementation method for your GA is through gtag.s, not GTM or analytics.js.
Thus you need to modify your success to:
#if (success)
{
<script type="text/javascript">
gtag('event', 'click', {'event_category': 'Supplier sign up', 'event_label': '/signup/success'});
</script>
<p>success message</p>
}
You have mixed two GA libraries. You use gtag.js for page view, so you need to use gtag.js (not analytics.js) for events.
https://developers.google.com/analytics/devguides/collection/gtagjs/events

google-analytics: Conversions not showing on Transactions

I have installed Google tag manager and the following tag is firing and being count accordingly for my E-commerce conversion (tag called 'Google Analytics eCommerce'):
<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-76425812-2', 'auto');
ga('require', 'ecommerce', 'ecommerce.js');
ga('ecommerce:addTransaction', {
'id': inspectionID
});
ga('ecommerce:addItem', {
'id': inspectionID,
'name': 'Inspection',
'quantity': 1
});
ga('ecommerce:send');
</script>
Nevertheless I am trying to create a tag and to avoid firing multiple tags for the same conversion. For that, I am creating a universal tag to save the utm_source and I am storing it on a Custom Javascript Variable.
TAG:
<script type="text/javascript">
var url = window.location.href;
var keyToFind = 'utm_source';
if(url.indexOf(keyToFind + '=') > -1)
{
var valueFound = url.substr(url.indexOf(keyToFind + '=') + keyToFind.length + 1).split('&')[0];
sessionStorage.setItem(keyToFind, valueFound);
}
</script>
Java Script Variable:
function()
{
return sessionStorage.getItem('utm_source');
}
When I use this variable to trigger any other tag (this is not triggering the Google Analytics eCommerce tag at all), GA stops considering the conversions.
Anyone may have an idea about what can be happening in the case?
Thanks,
Helton

Tracking of external links with Google Analytics

I have a problem with tracking external links. It's not like my solution does not work at all, the problem is, it works only in very few cases. Like 1% of clicks is actually tracked in Analytics. First I had the timeout set to 100ms and thought it might be too short, but even with 500 nothing changed.
Anyone has an idea what might go wrong here?
<script type="text/javascript">
(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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'domain.com');
ga('send', 'pageview');
</script>
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
ga('send', 'event', 'category', 'action');
} catch(err){}
setTimeout(function() {
document.location.href = link.href;
}, 500);
}
My links look like this:
a class="post" onclick="recordOutboundLink(this, 'Outbound Links', 'domain.com');" href="http://www.external.com" rel="nofollow">Click here
In Analytics I check in goals for "category = Outbound Links"
Thanks in advance!
There are a few issues with your code, but you should be using Universal Analytics built-in hitCallback function:
HTML:
<a class="post" onclick="recordOutboundLinks('Outbound Link', this.href); return false;" href="http://www.external.com" rel="nofollow">Click here</a>
JS:
<script type="text/javascript">
function recordOutboundLinks(category, link){
try {
ga('send', 'event', category, link, {'hitCallback': function() {
document.location.href = link;
}});
} catch(err){}
}
</script>
Looks like the issue is that you aren't preventing the default event for the link, so it doesn't matter what you set the timeout to.. your function gets executed but then the browser proceeds to execute the default event for the link: that is to follow the target specified in the href. You can update your code to this:
link (noticed use of event instead of this):
<a class="post" onclick="recordOutboundLink(event, 'Outbound Links', 'domain.com');" href="http://www.external.com" rel="nofollow">Click here</a>
function:
<script type="text/javascript">
function recordOutboundLink(event, category, action) {
try {
event.preventDefault(); // prevent default link action
ga('send', 'event', 'category', 'action');
} catch(err){}
setTimeout(function() {
document.location.href = event.target.href;
}, 200);
}
</script>
In my experience, a timeout of 100-200ms should be enough to get GA code to ping but you may have to play with that a little yet, because it's not guaranteed. Alternatively, you can write code to hook into when ga finishes its thing, and it would be easier if you are already using a framework like jQuery.. But overall I agree with Blexy in that you should switch to UA which provides a callback function (and in his example, he prevents the default by appending return false in the onclick).

Tracking anchor links - Google Analytics

I have a wordpress website and I'm tracking it with google analytics. I need to track the anchors and
have been digging stackoverflow to get some answers. After trying several, I still can't get it to work. So, what's wrong with this?
<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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-47361493-1', 'festasdelisboa.com', {'allowAnchor': true});
ga('require', 'linkid', 'linkid.js');
ga('send', 'pageview');
$(function(){
$("a[href*='http']").each(function() {
$(this).click(function (ev) {
var pageView = '/outgoing/' + $(this).attr('href');
_gat._getTrackerByName()._trackEvent('Outbound Links', pageView);
var _href = $(this).attr('href');
setTimeout(function() {
location.href = _href;
}, 100);
ev.preventDefault();
return false;
});
});
$("a[href*='mailto']").each(function() {
$(this).click(function (ev) {
var pageView = '/mailto/' + $(this).attr('href').substring(7);
_gat._getTrackerByName()._trackEvent('Mailto', pageView);
});
});
$("a[href*='#']").each(function() {
$(this).click(function (ev) {
var pageView = '/anchor/' + $(this).attr('href').substring(1);
_gat._getTrackerByName()._trackEvent('Anchors', pageView);
});
});
});
</script>
Was struggling with this for quite a while now. Use the below snippet as part of your Universal Analytics code - found it worked almost immediately for me! My GA reports are showing visits on hashtag anchors in the Behaviour >> Site Content >> Content Drilldown section
<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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-12345678-1', 'auto');
ga('send', 'pageview');
// Anchor Tracking snippet start
jQuery(document).ready(function () { var
hashtag = /#\S+/ jQuery('.menu li a').click(function(){ var match =
jQuery(this).attr('href').match(hashtag); ga('send', 'pageview', '/' +
match[0]); }) });
// Anchor Tracking snippet end
</script>
Found this to be the only workable and easily understandable solution - when it comes to Google's Universal Analytics

Resources