On all my site pages I have the google analytics async code setup as follows just before the closing head tag....
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-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>
Then on my checkout pages I am trying to use event tracking to report the time the user spent on the various pages as the value for google analytics events.
I am doing this by making use of the jQuery.ready function to record the 'start' time and add event handlers to the submit buttons that take the user to the next step in the checkout. This code is in a external file, common.js and is as follows...
$(document).ready(function() {
recordStartTime();
if ($("#checkoutPage1").length)
{
if ($("#customerDetailsForm").length)
{
// Time spent
$('.customerDetailsSubmitButton').click(function() {
time = durationWholeSeconds();
_gaq.push(['_trackEvent', 'Checkout', 'Timing', 'CustomerDetailsPage', time]);
return true;
});
}
}
I have similar sections of code for the other steps in jQuery.ready, #checkoutPage1, #checkoutPage2, #checkoutPage3 etc.
When I test this code on my browser (Chrome) all works as expected and using the ga.debug plugin I can see the _trackEvent parameters being sent to google analytics.
My problem seems to be that this does not always seem to work in the wild. On my live site I see intermittent events coming through. Given I know pretty accurately how many 'sales' I have the events that should be expected in GA do not match. Often some of the latter events in the checkout steps report without the earlier ones being recorded.
My question is basically can I use the jQuery.ready function to add the event handlers and the tracking code where needed? Is there another issue I am not spotting?
You can use jQuery.ready, but you have to keep in mind that sometimes jQuery.ready will not fire. Sometimes users will navigate away before the DOM is ready.
You didn't post your functions recordStartTime and durationWholeSeconds. If they raise an exception on a browser for some reason than that session won't fire events. Maybe you should make sure they are shielded by try catch blocks to fire the Event even if they fail.
I would also advise you to use $('.customerDetailsSubmitButton').mousedown instead of click. mousedown fires first and here timing is essential. If the browser redirects before the Event goes through there's a chance it will be canceled and never reach GA. In our tests using mousedown we see almost twice the hits than using click.
Related
On pageload does I load google analytics through he following code snippet:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("UA-XXXXXXXX-X");
pageTracker._trackPageview();
} catch(err) {}
</script>
And I use the following code to fire an event (after page load):
_gaq.push(['_trackEvent', 'test category', 'test action']);
Standard information get tracked, but NO CUSTOM EVENTS. I know all events get sent to Google Analytics because each time an event if fired, does an HTTP GET request get sent to the following url:
http://www.google-analytics.com/__utm.gif?.....more data here
What does I need to do to get custom events in google analytics to work?
Thanks in advance.
It seems you are running an old, "traditional", implementation of your Google Analytics.
I would strongly suggest that you upgrade to atleast the asynchronous snippet, where the syntax for _gaq.push is supported. As it stands now, you are trying to push an event using the new syntax into an old implementation which uses another syntax.
The differences between the two are detailed here: https://developers.google.com/analytics/devguides/collection/gajs/asyncMigrationExamples
In short, you are using a syntax for gat/pageTracker, where the newer asynchronous one uses gaq.
Please review this code that I have copied from above link:
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
...
<a onclick="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label', opt_value]);">click me</a>
To what you are using now, the older syntax:
var pageTracker = _gat._getTracker('UA-XXXXX-X');
pageTracker._trackPageview();
...
<a onclick="pageTracker._trackEvent('category', 'action', 'opt_label', opt_value);">click me</a>
As you can see, you are trying to send an event to the old ga.js using new ga.js syntax. I would highly recommend using the newer ga.js which loads asynchronously. By asynchronously, it means that the javascript loads while the webpage is loading, which the old ga.js does not.
This is an example implementation of the newer ga.js, and it should be implemented right before closing </head>:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-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>
If you implement the above suggestion, then you are using the newer ga.js and the _gaq.push-syntax should work. Try it out!
And if you do not know what the asynchronous part means, a brief explanation:
The latest version of the Analytics tracking code offers an improved way to track website visitors with Google Analytics. It takes advantage of browser support for asynchronous JavaScript to enhance the speed in which the tracking code is loaded. With the latest version of the tracking code, you can also place the Analytics snippet higher in the page without delaying subsequent content from rendering.
It continues to load other elements of your webpage aside from eachother, instead of waiting for 1 to finish before loading 2, then 3, etc.
I have set up GA event tracking on a test site I have. I use the asynch call in the page and then send events on click. the code I use is here:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXX-1']); // This is where my real Analytics Account number would be
_gaq.push(['_trackPageview']);
_gaq.push(['_trackEvent', 'AdvertImpression', 'MEA','logged In']);
_gaq.push(['_trackEvent', 'AdvertImpression', 'AN Other Advert','not logged in']);
(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);
})();
I also have an onclick event.
<IMG src="http://img.xxxyyy.com/banners/OPFME-20121211.jpg" width=468 height=60 border=0 alt="MEA" onclick="_gaq.push(['_trackEvent', 'AdvertClicked', 'MEA','Logged In'])")>
I see the site visits appear and my account says that events are being generated. When I select "Unique Events" I even see quantities but I cannot see any of the specific category information in the drill down.
I have remove all filters on the account and have waited for 48 hrs. Is there something I'm missing.
Google Analytics records data by making tracking image requests. If you're loading a new page in the same window before the tracking request has completed, no data will be recorded. I've had good luck with a slight delay before following the link.
Try the following code:
<script type="text/javascript">
function trackLink(link, category, action, value) {
_gaq.push(['_trackEvent', category , action, value ]);
if (link.target == "_blank") return true;
setTimeout(function(){ location.href = link.href; }, 150)
return false;
}
</script>
Add it the link as follows -- the return in the onlick is required.
<a href="http://www.xxxyyy.com/ad/click/taHR" onclick="return trackLink('AdvertClicked', 'MEA','Logged In')">...
Add target="_blank" to your <a> tag.
If the links you're adding tracking to could be added in a new window (e.g. if they are adverts or external links), then you can fix this by simply adding target="_blank" to your <a> tag to make the external link open in a new window.
This way you don't need to do any kind of delay (the original page keeps running and the javascript gets plenty time to complete) and you will always track your click - depending on network-speed/google load/various other things, 150 milliseconds may not be long enough to track the click resulting in fewer clicks.
Mostly, these types of clicks should be to external links anyway, otherwise you'd already have tracking in Google Analytics for these clicks since a new page would be loaded with your Analytics code on it.
<img src="http://img.xxxyyy.com/banners/OPFME-20121211.jpg" width=468 height=60 border=0 alt="MEA" onclick="_gaq.push(['_trackEvent', 'AdvertClicked', 'MEA','Logged In'])")>
If this still doesn't help, open your browser's javascript console - in Chrome hit CTRL+SHIFT+I then click the console tab - and check for any errors.
A problem I've seen elsewhere is _gaq is undefined which can happen if the Google Analytics script is not included properly on the page.
I made a small little Tic Tac Toe game that plays perfectly at http://tic.cwoebker.com.
The actual tic tac toe game is loaded from (/tic) and embedded in an iframe.
Therefore others could easily embed the game on their own site if they wanted.
I am doing some event tracking inside of the iframe.
Right now I have it setup so it fires a page view on both the main page
and the actual game code inside the iframe.
I was wondering whether I could somehow only fire the page view for the iframe if its not
embedded on http://tic.cwoebker.com but on another site.
So that everything thats tracked under root (/) is traffic on my site and everything tracked in the i frame (/tic) traffic generated by embedding on another site.
Right now my analytics code in the iframe looks like this:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxxxx-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>
Thanks a lot in advance.
As you're in an iFrame on a separate domain, you can't access the parent window to get the location. Check out this demo and/or google it a bit: http://jsfiddle.net/TomFuertes/RRB52/2/
_gaq.push(['tictactoe._setAccount', 'UA-xxxxxxxxx-x']);
// Line below causes security issues, thus won't work
_gaq.push(['_setCustomVar', 1, 'Domain', window.parent.location.host, 3]);
_gaq.push(['tictactoe._trackPageview']);
You can pass the domain using a querystring on your iFrame page, you'd need to modify the include code to look like this: https://stackoverflow.com/a/5697801/94668
<script type="text/javascript">
document.write('<iframe src="//tic.cwoebker.com/?url=' + window.location + '"></iframe>');
</script>
Then you'd filter out your Google Analytics appropriately.
You can use Google Analytics campaigns to track the traffic. You will need to distribute the embed code that already has the campaign parameters as part of the embed iframes src.
Hope that helps.
Interested to hear from others.
We started the A/B experiments on our site. Homepage is the tracking site and it redirects to 3 other versions. Since the google analytics script (ga.js) is loaded just after the site is redirected, we are loosing the referrals data. The referral is always the original homepage.
I was not successful in searching for the clear and right solution.
How can I provide the referral to analytics?
Thanks in advance.
EDIT:
So I tried _setReferrerOverride method, but didn't help.
This code is before the control script (the enter page for visitors, i'm lookinf for referrer here). I'm setting the cookie.
if($_COOKIE[abtestRef]) $_SERVER[HTTP_REFERER] = $_COOKIE[abtestRef];
if($_SERVER[REQUEST_URI]=='/'):
setcookie('abtestRef',$_SERVER[HTTP_REFERER],time()+300,'/','cloudee.eu');
<!-- Google Website Optimizer Control Script -->
<script ....
And here is the tracking script on page which the control script redirects to. So I'm setting referrer from cookie here ... but there is no change in GA, so probably I'm doing something wrong.
<!-- Google Website Optimizer Tracking Script -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['gwo._setAccount', 'UA-27591323-1']);
_gaq.push(['_setReferrerOverride','<?=$_COOKIE[abtestRef]?>']);
_gaq.push(['gwo._trackPageview', '/2713975509/test']);
(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>
Crayon is right. Here's an example snippet that works on my site:
_gaq.push(['gwo._setAccount', 'UA-XXXXXXXX-2']);
if (window.location.href.indexOf('ref=lowcost') >= 0) {
_gaq.push(['_setReferrerOverride', 'http://www.lowcostairlines.nl/']);
}
_gaq.push(['gwo._trackPageview', '/1794361722/test']);
To sum up, you will need to pass the original referring URL to the test page, and then manually set the referring URL on the test page.
You can do this by setting a cookie on the redirect page and then looking for it on the test pages, or pass via URL param. You will then need to use _setReferrerOverride() in your GA code to override the default (document.referrer) with the original referring URL.
You will also need to make sure you are passing all other URL params to the test pages as well, so you don't lose your campaign codes, etc.. if you use those.
I am using Google analytic on my web site.I have the following script in the head section of my page -
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-17301453-1']);
_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 am using the following method to track the number of clicks -
Grab This Deal
But the google anayltics website does not seem to be reporting any events/clicks. Please help.
When debugging you may like to either use the Firefox Live HTTP Headers plug-in or Wireshark. These will tell you about requests to Google Analytics.
Depending on the browser and the way the site loads it may be worth using the onload handler of the page to call the Google Anayltics code (with async set to false in the GA snippet) and dynamically assign the onclick event (an id on the tag will help find it). This will ensure the code can run at the appropriate time.
The link may be processed before the tracking event is sent to Google Analytics as you do not return false to the onclick event. AFAIK there is no callback on GA events to let you know when to proceed with the next page.
In short this looks like a race condition between an async GA request and the browser finding the linked site.
The only way to have this functionality would be to use an iframe or new window for the link's target.
does it work if you do this?
Grab This Deal
If so, you may need to put something in to wait for the google tracking code to complete before allowing the browser to navigate away.
have you tried adding return true; to the end..
Grab This Deal
Dunno if it will help, just a suggestion.