Just wondering how google analytics code snippet works in terms of javascript programming.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_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);
})();
</script>
1) We push 2 elements onto _gaq array but when does it actually get executed/used especially since ga.js is sitting on remote server? I tried looking into ga.js code but it's really confusing.
2) What would happen if the site was https:// but we still linked the javascript as http://www.google-analytics.com/ga.js
(function() {
var ga = document.createElement('script');
ga.src = 'http://www.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
_gaq is a global variable (in browsers global variables are stored in Window object)
And its referenced in https://ssl.google-analytics.com/ga.js like this:
var He = function () {
var a = W._gaq,
b = l;
if (a && Aa(a[p]) && (b = "[object Array]" == Object[y][w].call(Object(a)), !b)) {
Z = a;
return
}
W._gaq = Z;
b && Z[p][xa](Z, a)
};
Also W refers to Window global variable (the script is minified to save bytes):
var W = window,
For your convenience, I have pasted a formatted version of ga.js here:
http://pastebin.com/sBmeSg9M
Look at line 603 and line 1956.
The Google Analytics code gets loaded and run on your page, at your domain, hence it has access to window and all the variables defined on it. _gaq is the magic variable name that Google's code inspects when it runs to see what has been defined and uses the values it finds to begin tracking things. It then tracks changes to this variable for the duration your page is loaded (which is how it does click event tracking etc).
As others have mentioned, failing to use the HTTPS URL for Google Analytics on a page served over HTTPS will lead to a warning about "insecure content". Stick with the code Google provides, they do so for a reason.
2) What would happen if the site was https:// but we still linked the javascript as http://www.google-analytics.com/ga.js
This would prevent nearly all modern browsers (e.g. Chrome) to load the JS file and show a little warning to the user that there is "Insecure content".
The reason behind this is, that loading the JS file would allow MITM attacks without a SSL certificate warning.
2.: Then your SSL-certificate doesn't work correctly. There is non-ssl (https) script included to your SSL-site. Is that what you mean?
Related
I have a javascript widget that contains a google analytics loading code. There is already google analytics loading code on the html page where the javascript is going to live. The ga.js files are loading twice and the bounce rate has gone to less than 1% due to the multiple loading of ga.js.
Is there a javascript solution where I could check if the page already has ga.js loaded then skip the loading within the javascript widget file and load ga.js if it is already not loaded?
This is the code i'm using but it seems to load the ga.js again even if the page already has ga.js.
Note: The javascript widget that contains the below code is loaded within a document.ready call and the google analytics loading code is present within the head tag of the html page.
function loadtracking() {
window._gaq.push(['_setAccount', 'UA-XXX']);
window._gaq.push(['_setDomainName', window.location.hostname]);
window._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);
})();
}
if(window._gat && window._gat._getTracker && typeof _gat != 'undefined'){//if site already has google analytics loaded
var _gaq = _gaq || [];
window._gaq.push(['_setAccount', 'UA-43609253-2']);
window._gaq.push(['_setDomainName', window.location.hostname]);
}else{ //if site DOES NOT have google analytics loaded
var _gaq = _gaq || [];
loadtracking();
}
[cross-posted on Google Products Forum http://productforums.google.com/d/topic/analytics/ZrB14a-6gqI/discussion ]
I am using the following code at http://www.cs.bris.ac.uk/Research/Algorithms/
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-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);
})();
</script>
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', category , action ]);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
which I just copied directly from http://support.google.com/analytics/bin/answer.py?hl=en&answer=1136920 .
However, it doesn't actually seem to report any clicks on the links where I have added onClick="recordOutboundLink(this, 'Outbound Links', 'Postdoc advert');return false;", for example. I have seen a number of complaints about this online but I haven't found a solution that works.
What am I doing wrong?
P.S. The closest related online complaint seems to be http://productforums.google.com/forum/#!topic/analytics/4oPBJEoZ8s4 which just claims the code is broken.
Here's what I'm using, which has been working for me. I'm using jQuery to add the onclick handler to any link with a class of "referral", but I'd expect adding it directly in the HTML to work as well.
$(function() {
$('.referral').click(function() {
_gaq.push(['_trackEvent', 'Referral', 'Click', this.href]);
setTimeout('document.location = "' + this.href + '"', 100);
return false;
});
});
edit: I believe your syntax for invoking a tracker by name is wrong. Since you aren't using a named tracker when you set up tracking at page load, you shouldn't try to name it later either. See the documentation for _gaq.push.
More precisely:
The var myTracker declaration is unused, so you can just delete that line. Variables declared within the scope of recordOutboundLink aren't visible when other functions, such as _gaq.push, are running, so it can't be relevant.
You should simply use '_trackEvent' instead of 'myTracker._trackEvent'.
You can also try this automated external link script
Set a longer timeout 2 seconds maybe, as it takes a certain amout of time for the _gaq.push to actually push to the server, and 100 milliseconds isnt long enough for it to send (the push gets cancelled as soon as the document.location changes). Unless _gaq.push uses a blocking call (doesnt execute the next line till the push is complete), but i dont think that is the case i think most of that uses asynchronous requests.
I've been trying to find a solution for this but haven't seen anything useful google'ing around. The issue might be that i'm using terminology that has other meanings.
I have a site that has utilizes the same URL's for both guests and members. In order to track visits and goals correctly i need a way to tell if the visitor is a logged in user or a guest.
The easiest way i can think of is if i just prefix my URL's with something like
/member/
I thought maybe i could do this in the google tracking code by adding this:
_gaq.push(['_trackPageview'], '/member' + window.location.pathname);
the full code is:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'xxxxxxxxxx']);
_gaq.push(['_trackPageview'], '/member' + window.location.pathname);
(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>
However this isn't working, also reading the google analytic docs, this seems to be a way to add an 'additional' page view.
I can update the servers code to prefix the urls with /member/ and then strip it before processing the path for the controllers, but i would rather not risk breaking a stable system thats about to go live.
Does anyone know how this can be done in JS before the normal URL is tracked?
Thanks,
Dan
You have a minor syntax error with your _trackPageview call.
It should just be this:
_gaq.push(['_trackPageview', '/member' + window.location.pathname]);
Note that the /member+ part is now within the array, not outside of it.
What you were doing was passing the _trackPageview function name without a second parameter to be its argument (which, by default, tracks the pageview as location.pathname+location.search, and then passing a string /member+window.location.pathname to the array, which did nothing.
Passing the custom URL as a 2nd item in an array will make it work just fine.
Aside from the fact that you probably shouldn't use the same URL structure for goal tracking in Google Analytics, I can suggest a couple of ways to solve the problem. Note that this doesn't address the alias-tracking question you asked, but offers some alternatives.
1. Append a querystring parameter to goal pages for members or guests
Bit of a hack, but it should be trivial to append a ?guest=true param if your users are not logged in. This would be a minor change that should not affect your business logic or website operation.
You can then set different goals in GA that look for the success page with or without the URL param.
2. Set custom variables in Google Analytics for members and guests
This is the more correct solution.
Use session-level custom variables to distinguish different visitor experiences across sessions.
For example, if your website offers users the ability to login, you can use a custom variable scoped to the session level for user login status. In that way, you can segment visits by those from logged in members versus anonymous visitors.
http://code.google.com/apis/analytics/docs/tracking/gaTrackingCustomVariables.html#sessionLevel
Then you can segment your goal starts and completions using your advanced segments, segmenting on user login status:
http://www.lunametrics.com/blog/2010/10/07/visitor-signed-in/
I am attempting to add google analytics tracking to an Adobe Air app created with HTML and javascript.
I have tried adding the ga.js file and using it like I would in a webpage:
<script type="text/javascript" src="lib/js/ga.js"></script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-********-1");
pageTracker._initData();
pageTracker._trackPageview('/test');
</script>
But this doesn't seem to register anything on the analytics dashboard.
Have also tried using the GA for flash actionscript library but I can't seem to create an instance of the GATracker as it needs a DisplayObject?
EDIT
using the information from grapefrukt I tried the following:
air.Sprite = window.runtime.flash.display.Sprite;
air.GATracker = window.runtime.com.google.analytics.GATracker;
var tracker = new air.GATracker( new air.Sprite(), "UA-XXXXXXX-X", "AS3", false );
but I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null object reference
NOTE: I originally misread your question to be about how to use gaforflash, but I'll post this anyway since I've already typed it up and it might be of some use.
You can the constructor whatever DisplayObject you like, normally you'd use your document class, but anything will work. As far as I can understand it's only really used for displaying debug info.
var tracker:AnalyticsTracker = new GATracker( new Sprite, "UA-XXXXXXX-X", TrackerMode.AS3, false );
Setting the TrackerMode to AS3 let's the flash communicate directly with the tracking servers, so you don't need the javascript from google's servers.
I can't help you with the communication between js/as3, but that should be fairly easy.
Probably not useful to the OP, but just spent the whole day working around this so hopefully my solution will save someone else that time.
So the reason the ga.js code can't be used directly from an AIR app written in javascript is that AIR won't set the cookie for pages that are stored within the application itself. To work around this, I downloaded ga.js to the application and modified it so that it doesn't rely on the document.cookie function.
In the application, I have:
<script type="text/javascript">
var cookies = {};
document.__defineSetter__('_cookie', function(c) {
var epos = c.indexOf('=');
var spos = c.indexOf(';', Math.max(0, epos));
if (epos == -1 || spos == -1) { return; }
var name = c.substring(0, epos);
var value = c.substring(epos + 1, spos);
cookies[name] = value;
});
document.__defineGetter__('_cookie', function() {
var a = [];
for (var name in cookies) {
a.push(name + '=' + cookies[name]);
}
return a.join('; ');
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-1']);
_gaq.push(['_trackPageview', path])
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
// custom GA code which uses document._cookie instead of
// document.cookie
ga.src = 'js/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
Ideally, we'd be able to override the cookie method, but unfortunately, it doesn't seem possible in webkit as implemented for AIR. So in ga.js, I replaced all instances of J.cookie with J._cookie. Once that's done, ga.js should believe that it's writing cookies and function normally.
In the interest of full disclosure, I actually access the above analytics code through an iframe, but since ga.js is being served locally, I suspect it's no longer necessary and didn't want to complicate the solution by adding the bridge logic.
Wonder if somebody is able to clarify the following;
Using the aysnc google analytics code placed in the head of the document as follows
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456-1']);
_gaq.push(['_setDomainName', '.somedomain.co.uk']);
_gaq.push(['_trackPageview', pageUrl]);
(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);
})();
On some the pages I am tracking I also use custom events to track video plays and which forms are used. These events use a further _gaq.push() call at various points on the page.
My question is should the final section of the initial analytics code (the section that calls ga.js be split and placed at the end of the page code or will any calls made once the script has loaded still be passed to Analytics regardless of the position on the page.
Thanks in advance.
No, the final section of the initial analytics code need not be placed lower down. You can call as many _gaq.push() calls as you like throughout the page, they'll still successfully pass to analytics.
The _gaq.push() event calls will send new requests to Google Analytics in addition to the first one you make (_trackPageview). You can check those event calls my inspecting how many requests your page makes for _utm.gif in a tool like Firebug.