Tracking Multiple Domain Names Under One Google Analytics Account - javascript

I've read the docs here about 100 times and I can't figure this out.
I have a platform that basically creates spoofed domain names on top of one backend:
mysite.com
yourface.com
example.com
Since all domains point to the same root index file, I would like to have one Google Analytics tracking code that I can put in the footer that will track activity on all these domains.
Right now, I am using the following, and it only tracks activity on mysite.com (not the other ones):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_setDomainName', 'mysite.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_getLinkerURL','mysite']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
I know I can set up separate profiles but that defeats the point of needing aggregate data.
Any ideas?

The culprit is probably this
_gaq.push(['_setDomainName', 'mysite.com']);
because that limits the GA cookie to the mysite.com domain. If you drop the setDomainName call alltogether it should track all domains where the code is deployed (and you'll need to filter by hostname if you want to see data for one particular domain).
That is, if I understood you correctly and your domains use the same backend but are independent on the frontend; if there is traffic between the domains you'll need to set up cross domain tracking to track correctly (else user sessions will end when a user visits another domain).

From the Google Analytics dashboard, click on Admin at the right to get to the Account Administration page. Then click on the name of your account, and you'll be taken to a list of things you're using Analytics to track. Then click on the New Property button to add the next website to your account. Each website gets its own javascript code that must be generated by Google Analytics before you install it in your website, so you have to go through this process for each website you want to track.

Related

Google Analytic inside iframe

I have an iframe that hosting a third party page (that I build). In that page, I have a Google analytic as below. However, Google analytic is not tracking all the entries...
The third paty page redirects users to different pages depending on different times of the day. Is there anything extra we need to do to implement Google Analytic in an iframe?
(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-47306399-1', 'serviceportal.com.au');
ga('send', 'pageview');
If the page within the <iframe /> element is on a different domain than the parent page, then you'll run into problems (particularly with older versions of Internet Explorer). The issue is that 3rd party cookies are blocked when there isn't a correct P3P header for every external asset loaded on the page within the <iframe /> (including the HTML document itself). This will effectively break your tracking code since it relies on 3rd party cookies (i.e. cookies created for domains controlled by Google or whatever other tracking provider you use).
If this is your issue, I've found two fixes.
Output proper P3P headers for all assets loaded inside the IFRAME so browsers don't block 3rd party cookies.
Use JS to Communicate from the inner-page to the parent-page and then use that communication to trigger tracking pixels from the parent-page.
My guess is that there are other ways to do this as well, this is what has worked for me.
Also, note that you can do as little as change the protocol and the pages will be thought of as on different domains by the browser, so it's generally a good idea to load the IFRAME with a URL starting in // rather than http:// or https:// so that the protocols of the parent-page and the inner-page will match. This is just if they are on the same domain to start with.
Another note... Please DO NOT just copy/paste any old P3P header value into a production environment just because it makes the "evil eye" go away in IE. Specific P3P header "codes" equate to real privacy policy statements.
One of the SEO gurus at my workplace was able to provide me with the solution tips
It was a fact of misamtached server..
The correct code ended up being
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-47544250-1']);
_gaq.push(['_setDomainName', 'vserver.com.au']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

How can I make sure _gaq.push() works good?

Our client asked us to implement the following Google Analytic code:
_gaq.push(['SX0._setCustomVar', 4, 'xxxx', "yyyy", 2]);
So I've made this, and now I'm looking for a way - how can I check that everything is correct (without actually building GA report)? I haven't did this before - so please sorry if the answer is obvious.
Thanks.
You'll need to define the _gaq variable and load in the analytics script from googles server. After that, you should be able to call the 'push' method.
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// tracks hit for /some/page/
_gaq.push(['_trackPageview', '/some/page']);
After that's done, load up the page in your browser, open up the console, and look in the network tab. Try loading a few pages, and verify that it's asynchronously pushing data to googles servers.
Google uses a .gif image for tracking, so you might try filtering by image and to find request for a file called __utm.gif
If you're still having trouble finding it, you might try the tag debugger plugin by ObservePoint for Chrome or the Official Tag assistant plugin by Google
Use the Analytics debugger extension for Chrome. Another useful extension (although it will not help you with custom vars) is the Google Tag Assistant (which will also check other Google tags such as adwords conversion tags and the like).

Do i need a running website over internet in order to access Google analytics Data using Google API

I am new to Google analytics API. I want to access my Google Analytics Data using its API.I have a local website which is deployed on IIS over a LAN.Using this setup can i access google analytics data by using its API or i need a website running over the internet.If yes please suggest how can it be done using javascript.
Google Analytics works by sending information to Google servers whenever someone visits your HTML page (doesn't need to be on the web). However you need access to the internet to send data to the Google servers. You can track any "website" if you make an account on Google Analytics and simply add the code below to whichever page you wish to track (before the </head> tag, as Google says):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'TrackingID']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
The TrackingID must be replaced by the tracking ID for your Google Analytics account.

Is there a setting on Google Analytics to suppress use of cookies for users who have not yet given consent

According to EU Article 5(3) of the E-Privacy Directive (a.k.a 'The Cookie Laws'), web sites that target EU users have to gain opt-in consent from users before they set a cookie.
See ICO Guidance
I am trying to square this with Google Analytics on my web site.
I would imagine that Google Analytics (GA) can do a certain level of analytic data gathering without requiring the use of cookies.
However, I cannot find any info on this (on the Google sites/settings panels) about how to relay information about the 'state of consent' back to Google during a page request. So, my only option seems to be that I should not embed Google tag code at all if the user has not explicitly given consent. Which seems a bit drastic.
Letting my serverside script set a hasConsentedToCookies=FALSE flag in the JavaScript tags would allow me to instruct Google's services to run in a gracefully degraded fashion.
Is there a setting on Google Analytics to suppress use of cookies
for users that have not yet given consent?
If so, where can I find info on this?
EDIT (2019): The below answer predates GDPR and likely requires revision.
Google Analytics has a new set of APIs to assist with compliance with a cookie opt-out. Here's the documentation, and here's their help docs.
There has been some ambiguity as to whether the EU Cookie Regulations (as implemented in member countries) require that passive web analytics tracking requires opt-in mechanisms for compliance. If you're concerned one way or another, consult an attorney. Google is empowering you to make the decision as to how you want to proceed.
They'll leave implementation details to you, but, the idea is, once you've determined whether or not to track the user in Google Analytics, if the answer is to not track, you'd set the following property to true before Google Analytics runs:
window['ga-disable-UA-XXXXXX-Y'] = true;
Where UA-XXXXXX-Y is your account ID in Google Analytics
As the other posters have noted, Google Analytics relies on cookies. So, you're not able to do any kind of tracking without cookies. If you've determined that someone is not to be cookied for tracking, you'll need to implement something like this:
if(doNotCookie()){
window['ga-disable-UA-XXXXXX-Y'] = true;
}
Opt In
This does require a little bit of jujitsu for when you first load Google Analytics, since this property will need to be set before Google Analytics runs to prevent tracking from ever happening, which means, for an "opt in to tracking" approach, you'd probably need to implement a mechanism where, on first visit, Google Analytics is automatically disabled in the absence of an opt-in cookie (cookies that determine cookie preferences are explicitly allowed), and then, if an opt-in happens, re-runs Google Analytics. On subsequent pageviews, all would run smoothly.
Could look something like (pseudo-code):
if( hasOptedOut() || hasNotExpressedCookiePreferenceYet() ){ //functions you've defined elsewhere
window['ga-disable-UA-XXXXXX-Y'] = true;
}
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-Y']);
_gaq.push(['_trackPageview']);
function onOptIn(){ //have this run when/if they opt-in.
window['ga-disable-UA-XXXXXX-Y'] = false;
//...snip...
//set a cookie to express that the user has opted-in to tracking, for future pageviews
_gaq.push(['_trackPageview']); // now run the pageview that you 'missed'
}
Opt Out
With this approach, you'd allow the user to opt-out of tracking, which would mean you'd use a cookie to set the ga-disable-UA-XXXXXX-Y' property and a cookie to manage it in the future:
if( hasOptedOut() ){ // function you've defined elsewhere
window['ga-disable-UA-XXXXXX-Y'] = true;
}
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
_gaq.push(['_trackPageview']);
You can disable the use of cookies for Google Analytics by specifying the {'storage' : 'none'} option when creating the tracker instance.
See Google's guide on the subject for more details.
I often never ask users to opt out for google analytics, that is because i never set cookies and i never save their ip (and other personal data).
(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-98765432-1', 'www.example.com', {
'anonymizeIp': true
, 'storage': 'none'
, 'clientId': window.localStorage.getItem('ga_clientId')
});
ga(function(tracker) {
window.localStorage.setItem('ga_clientId', tracker.get('clientId'));
});
ga('send', 'pageview');
Also check out this code at Convert Google Analytics cookies to Local/Session Storage
This script will not set any cookies, but still track via google analytics. This will actually have the same effect on privacy as using cookies, because google still records the users IP-address.
That is where the anonymizeIp switch comes in. This tells google to only save an anonymized version of the IP-address. An anonymized IP-address is not considered personal data, so the users privacy will be respected.
AFAIK cookie law is all about privacy and does allow website to track their usage. I am not a lawyer or anything but in my opinion this script complies to the EU cookie law.
Check out this plunk to see it in action: http://plnkr.co/MwH6xwGK00u3CFOTzepK
As a quick note, the BBC (probably the most popular site in the UK) has taken an interesting approach to complying with cookies - they've displayed a banner to users telling them that cookies are set and provide a couple of links.
This one explains what cookies are. This one lets them manage their cookies, but most interestingly of all they supply a link to Google Analytics to allow users to opt-out of GA in its entirety. So, in summary, the BBC have taken the view that they can tell the user what cookies are set and then provide a link to Google to allow the user to opt out of all GA cookies. For me, that's a lot less hassle than you telling GA to opt-out for an address through JS.
Latest Google Analytics (gtag.js) has a "Consent mode" just for that (still in beta):
https://developers.google.com/gtagjs/devguide/consent
It looks like this:
gtag('consent', 'default', {
analytics_storage: 'denied',
ad_storage: 'denied'
});
Then you can update these settings at a later time in the case the user consents.
You can disable google analytics cookies by adding this code at the top of google analytics code (before line: var _gaq = _gaq || [];):
ga('create', 'UA-XXXXXX-XX', {'storage': 'none'});
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
However some features of google analytics (for example real time stats) do not work properly after this modification. More about google analytics cookies: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains?hl=en#disableCookies
I was facing the same problem.
Eventually, I got a solution in the line of Elmer's reply but playing safe regarding IPs, that is without using localStorage
// Create a fake ID instead of storing anything locally
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
...
ga('create', 'UA-XXXXXX-Y', {
'storage': 'none',
'clientId': guidGenerator()
});
(-) Every page visited will count as a new visitor in Google Analytics, so I am losing quite a lot of functionalities there.
(+) But I can live with it and I believe I am safe regarding data privacy legislations.
Any feedback or improvement suggestion is more than welcome.
Common way to handle this so far is the method used by wolf-software's jquery plugin whereby it prevents the script from running until the user opts in. The ICO updated their guidelines last week, however, to say that it is acceptable to rely on 'implied consent' of the sort used on the BBC site. While I don't really think that's within the spirit of the law, it's what's deemed acceptable by those enforcing it. Given that most of the EU has yet to implement the directive, I'd say it's highly likely they'll follow the UK's lead.
There's an interesting article about the UK updates here:
http://www.redant.com/articles/eu-cookie-law-update-ico-adopts-softly-softly-approach/
EDIT: There is a Google Analytics setting for this with the Asynchronous GA snippet.
There isn't a Google Analytics setting for this, as you're suggesting, you would need to conditionally exclude the script for those that have not consented if you want to use the Google Analytics Javascript tracking script.
There are some solutions out there already that can be helpful instead of rolling your own.
Javascript: http://cookies.dev.wolf-software.com/demo/index.htm
Here is a solution that allows using Google Analytics basic features without cookies, by doing the tracking server side, this example is in PHP: http://techpad.co.uk/content.php?sid=205
For a less intrusive UX solution you can set implied consent for google analytical cookies by placing a link to: cookiestatement.eu (no javascript, no popups, no ads)
Sorry for being late to answer but I was looking for the same thing recently until I found out a way myself. It may not be the right way to do it but it works. (only works on site in question does not opt-out of GA completely).
I have tested for a few days to make sure.
The way I have managed to do it is using a PHP cookie. First start off with adding the analyticstracking.php include...
<?php include_once('analyticstracking.php'); ?>
and in analyticstracking.php add the following...
<?php
if($_COOKIE['consent_cookie']=="Y"){
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-********-*']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<?php
}
else{
//do nothing
}
?>
Before the user has consented to cookies Google Analytics won't work and once they have, the 'consent_cookie' will be saved and will allow GA to work but if the 'google' cookie is destroyed it will stop GA from working (Obviously).
Like I said it may not be the right way but I have tried and tested and it does. Hope this helps somebody.
Update 2022: Its not about Cookies anymore. Now you need a consent even for loading google fonts from outside the EU. This is because doing so the users IP (very private Information haha) will be send to the USA.
Im not a lawyer but this affects Adsense and Analytics as well. Here you will find a solution how to load Adsense and Analytics only if consent is given: https://stackoverflow.com/questions/70967060/loading-google-adsense-analytics-and-youtube-only-when-consent-is-given
Simply call setTimeout("analyticsladen()", 1); when consent is given:
The new Google Analytics 4 Code is:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-####');
</script>
<script type="text/javascript">
function analyticsladen() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.googletagmanager.com/gtag/js?id=G-####';
document.body.appendChild(script);
}
//setTimeout("analyticsladen()", 1);
</script>
Or you can use the old Google Universal Analytics Code. It will only work till June 2023 (says google):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-####-#']);
_gaq.push (['_gat._anonymizeIp']);
_gaq.push(['_trackPageview']);
var analyticsladen = function(){
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
}
</script>
Funfact: Google ranks my page 4 steps higher scince im not using analytics at all anymore :D
There's a few steps to do in order to make GA work only after user accepts the cookie usage.
Disable cookies
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-Y"></script>
-- <script>
-- window.dataLayer = window.dataLayer || [];
-- function gtag(){dataLayer.push(arguments);}
-- gtag('js', new Date());
-- gtag('config', 'UA-XXXXXX-Y');
-- </script>
At the point where GA is implemented, this needs to be updated by just importing the gtag.js script and removing the GA initialisation.
Enable GTag when user accepts cookies
GTag Opt In is a tool that enable and disable GA when user accepts/rejects cookies.
<script src="https://www.npmcdn.com/gtag-opt-in#2.0.0/dist/index.js"></script>
<script>
GTagOptIn.register('UA-XXXXXX-Y');
...
// On user opt in
GTagOptIn.optIn();
// On user opt out
GTagOptIn.optOut();
...
</script>
Library is loaded. GA tracking ID is registered. Later the optIn and optOut functions can bind to user actions' accept/reject.
You can read more about it on How To Implement Google Analytics With Opt In.
You can use something like Legal Monster - to block cookies if user didn't give consent for analytical cookies.
legal.js currently supports blocking (and enabling) of analytics and marketing cookies; more categories will be available in the future.
Here is more detailed guide on blocking cookies.
GA does not work without cookies, it needs it to 'identify s' the visitor if he/she visited your site before. So there is no setting in GA for this, GA just doesn't records the visitor if it cant create a cookie.
If the user is from the EU and has not opt-in then you should exclude the google-analytics script I think.

Disable Google Anayltics cookie from being sent to cookie less domain

To optimize my site i have set up a static subdomain for content such as images, css and javascript. How do i stop the google analytics tracking cookie from being sent to my static subdomain, but still to both example.com and www.example.com?
Have already looked through some of the documentation with no luck
You can't have a cookie that gets sent to www.example.com and example.com but not othersubdomain.example.com.
You can in theory have a cookie that gets sent to example.com but not subdomain.example.com, but it doesn't work in IE.
This is why you should not use a no-www example.com address when you are planning on using subdomains with their own security context. It's best to have only one of www.example.com and example.com as the ‘proper’ URL anyway. So set up a redirect for example.com to go to www.example.com, and cookies won't be shared unless you deliberately set domain=.example.com on them.
If you're having issues with Google Analytics creating a cookie for every domain, including your subdomain ones. Here's my solution that I've posted elsewhere on the subject.
By golly I think I've found a temporary solution to the broken code supplied by Google.
If you go into GA and get the non-async code and choose:
One domain with multiple subdomains
Examples: apps.konoro.org
store.konoro.org
video.konoro.org
You'll see that it gives you a code sample with .konoro.org. Change that to www.konoro.org and all cookies will have: .www.konoro.org (with a dot in front of them).
Now if you go back to your Async code, there's only one difference apart from being Async. You need to put ['_setDomainName', 'www.konoro.org'], as the second option rather than after ['_trackPageview'].
For some reason, with this being the second option, it works fine.
My final code is:
var _gaq = _gaq || [];
_gaq.push(
['_setAccount', 'UA-XXXXXXX-1'],
['_setDomainName', 'www.konoro.org'],
['_trackPageview']
);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();

Categories