I'd like to remove the Google Analytics URL tracking code from the browser bar so that when a user copy / pastes the URL to share they don't bring along all the tracking data with them, which is both useless and able to skew the data down the road.
So I'm using history.js to run replaceState to basically get rid of the tracking data from the URL after a brief pause.
<script type="text/javascript">
setTimeout(function() {
if( window.location.search.indexOf( "utm_campaign" ) >= 1 ) {
window.history.replaceState( null, document.title, window.location.pathname);
}
}, 1000 );
</script>
Does anyone see any possible complications or problems with such a method?
The only problem that you might have is that Google Analytics might not have been fully loaded by the time that your timeout code runs.
With the Google Analytics tracker, there is an API that lets a function be queued after the GA data has been sent off to Google.
You can do something like this:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
var newPath = location.pathname + location.search.replace(/[?&]utm_[^?&]+/g, "").replace(/^&/, "?") + location.hash;
if (history.replaceState) history.replaceState(null, '', newPath);
});
(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);
})();
Notice line 4, where a function is pushed to the _gaq object.
This function will replace the URL straight after the GA request has been sent.
Related
ok, so, I have been trying to make _gaq.push work since so long now.
And my corresponding code is as below.
var ext_id = localStorage.ext_id;
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxx-xx']);
_gaq.push(['_trackPageview']);
//console.log(_gaq);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = chrome.extension.getURL('js/ga.js'); //uncomment this
//ga.src = "js/ga.js"
// ga.src = 'https://ssl.google-analytics.com/ga.js';
document.head.append(ga); // make it head
// var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); // comment this out
})();
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "google-analytics");
port.onMessage.addListener(function(response) {
console.log("Message Passing with response",response.category,response.action, response);
// _gaq.push(['_gat._forceSSL']); // remove this
_gaq.push(['_trackEvent', response.category, response.action,ext_id]); // trouble shoot this
console.log(_gaq, "sending this");
});
});
so, the above will be run when there's no activity on the payments page for more than 1 second. And its triggering properly, i.e its executing after 1 second of inactivity on payments page. But, but _gaq.push is showing no trace in the network tab, to make it more obscure, I'm not even getting any error. Can someone pls tell me what I could possibly be doing wrong?
The gaq.push looks fine and should work.
I think your ga.js library is not loading. Maybe since getURL is deprecated? https://developer.chrome.com/extensions/extension#method-getURL
On a site I'm working on, the main section of the tracking code is located at the bottom of the pages (not my choice of placement, but that's where it is). That code is the main:
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);
})();
On one specific page, I want to track an event that gets auto launched on page load. What I have for code at the top of the page (and therefore in a separate tag than the above code) is:
function getFile()
{
if("<%= getFileURL()%>".length>0){
window.location.href = "<%=getFileURL() %>";
var _gaq = _gaq || [];
_gaq.push(['_trackEvent', 'Downloads', '<%= getFileURL()%>']);
}
}
It doesn't seem to be tracking the event though. I'm sure I'm doing something wrong here and I can take some guesses, but it's not clear enough for me to know exactly what I need to change.
Two problems with your code:
You're redirecting before tracking the event. For best results (like #EkoostikMartin mentioned), you'll want a slight delay between the event tracking and redirect.
You've got a local _gaq defined inside getFile(), so you're not talking to the actual Google analytics code.
Try:
function getFile() {
var href = "<%=getFileURL() %>";
if (href.length > 0) {
_gaq.push(['_trackEvent', 'Downloads', href]);
setTimeout(function(){window.location.href = href}, 100);
}
}
You need to delay the redirect. Something like this below has worked for me in the past:
function getFile() {
var href = "<%=getFileURL() %>";
if(href){
_gaq.push(['_trackEvent', 'Downloads', href]);
setTimeout("gotoUrl('" + href + "')", 100);
}
};
function gotoUrl(href) {
window.location.href = href;
};
Going out of my mind on this one.
I have Facebook like buttons on my ecommerce store. I have set them up using the XFBML and JAvascript SDK.. I am using the correct Meta OG properties.. everything work fine for facebook.
Now this is where it goes wrong: I was trying to follow this guide: http://www.websharedesign.com/blog/how-do-i-track-that-little-facebook-like-button-in-google-analytics.html but it doesn't work for me as there a couple of differences. Firstly Im using the Async version of Google analytics... Secondly, my facebook like buttons get the URL automatically (In this article the user has manually put in the href...) So i changed the code to add in the gaq.push method instead;
I have tried adding:
FB.Event.subscribe('edge.create', function(href, widget) {
_gaq.push(['_trackEvent', 'facebook', 'like', href]);
});
into the main Async Facebook script, i have tried putting this on its own at the bottom of the page.. I have even tried adding this as an onclick= on the actual fb:like.
The only time i got it to register anything was when i accidentally added that code in my main Google analytics and then it generated a report for every page view as an event...
Please help!!
EDIT this is all my code: I have GA at the top of my page...
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'xxxxxxxxxxxxxxx']);
_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 below this FB is defined at the top of the body:
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
alert('Facebook Like');
_gaq.push(['_trackEvent', 'facebook', 'Facebook like', 'test']);
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
You see I have a put the gaq.push in the facebook code above - with an alert. Now this alert is fired when i click like, but the trackEvent is not sent to google? (Also, ideally where it says 'test' I would like the URL of the page...)
Thanks guys.. after 7 hours i worked out what the problem was... I had my IP hidden from Google Analytics as i didn't my test visits to mess up the stats of th regular pageviews.. So i learned the hard way that it also hides your IP addres from track Events! For reference the code that I supplied before works perfectly.. the only thing I changed was the changing the 'test' to url to get the href of the page being liked, so my final Facebook code was:
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
alert('Facebook Like');
_gaq.push(['_trackEvent', 'facebook', 'Facebook like', href]);
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
What a muppet! Thanks for your help though!
I read this article about tracking outbound links on banners and such:
http://seogadget.co.uk/how-to-count-your-outbound-click-stats-with-onclick-in-google-analytics/
So I added this code to the onClick event of my href:
javascript: pageTracker._trackPageview('/outbound/top_banners/banner_name');
Is this enough?
Because I have read some places I need a "link delay" function or something in the HEAD of my document as well, before any javascript is executed!
Also, where exactly in GA (in the interface) will I be able to view the clicks?
Thanks
Here's the problem: every item of data recorded & reported by Google Analytics is sent to the GA Servers in the Request URL component of a Request by the client for the __utm.gif. The function _.trackPageview() provokes the collection/concatenation of the data into a Request URL, as well as the Request itself. In other words, if _trackPageview() isn't called, no data is sent to the GA Servers.
So the question is whether the GA Request (above) is processed before the Request associated with the outbound link. If it is not, then the click on the outbound link is not recorded by GA, which is not what you want.
So what you want to is delay, just slightly--long enough for the GA Request to occur but short enough so that the user doesn't notice the delay--the outbound link Request.
There are a few differences between the code posted in your Q, and the code below--all diffs are directed to this 'race condition'.
First, notice that the return value from the onClick handler is set to "false"--preventing the client browser from (immediately) navigating to http://www.outbound-link.com
The second diff is the call to setTimeout. The third argument passed in, '100' is the number of milliseconds delay.
Third, the onclick handler (fnx) creates its own tracking object, and therefore doesn't rely on a pageTracker object to have been initialized elsewhere.
Your second question is, where in the GA Browser do you view these clicks? Using GA, you can track events in two distinct ways--using _trackEvent() or _trackPageView().
By tracking outbound links the second way (as you did and therefore as i did below) the 'click' shows up not as an event, but as a pageview ('virtual pageview' is the term most often used by the GA Consultants, et al. to indicate something tracked as a page view but which is actually not). So you will see these clicks reported along with other page views--i.e., in Content (along with Traffic and Visitors, the three main headings in the left-hand panel). How can you tell which lines in that report refer to the these outbound clicks? The value of the Page field (usually the left-most column heading) will be the url of the outbound link. Once you know this, of course, you can create an Advanced Segment or Custom Report or even a new Profile, to report these separately.
<script type="text/javascript">
function fnx(that) {
try {
var pageTracker=_gat._getTracker("UA-YOURACCOUNTHERE-PROFILE");
pageTracker._trackPageview("http://www.outbound_link.com");
setTimeout('document.location = "' + that.href + '"', 100)
}catch(err){}
}
</script>
<a href="www.outbound_link.com" onclick='fnx(this);return false;'>"Take Me Here"</a>
This is my 100%-working solution for tracking all outbound links (I love jQuery, so you need to add jquery.js script to page).
function isLinkExternal(link) {
var r = new RegExp('^https?://(?:www.)?' + location.host.replace(/^www./, ''));
return !r.test(link);
}
$(document).ready(function() {
$(document).bind('click', function(e) {
var target = (window.event) ? e.srcElement : e.target;
while (target) {
if (target.href) break;
target = target.parentNode;
}
if (!target || !isLinkExternal(target.href)) return true;
var link = target.href;
link = '/outgoing/' + link.replace(/:\/\//, '/');
_gaq.push(['_trackPageview', link]);
});
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-YOURCODE-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);
})();
This script give all outbound links to GA like: /outgoing/http/www.example.com.
For better experience you need to create advanced segment for this links. Create it with parameters: "Page" "Starts with" "/outgoing/http".
That's all! Now you have full statistics for your outbound links.
This solution will allow you to click links with target='_blank' and additionally, will allow you to set data attributes on any link and have those automatically send up to GA.
$('a').bind('click', function( event ) {
var target = $(this).attr('href');
if ($(this).attr("data-event-category") !== undefined && $(this).attr("data-event-label") !== undefined) {
gtag('event', 'click', {
'event_category': $(this).attr("data-event-category"),
'event_label': $(this).attr("data-event-label"),
'event_callback': function(){handle_redirect($(this), event);}
});
} else {
handle_redirect($(this), event);
}
});
function handle_redirect(element, event) {
var target = element.attr('href');
var regExp = new RegExp("//" + location.host + "($|/)");
var isLocal = (target.substring(0,4) === "http") ? regExp.test(target) : true;
var url = target;
if(isLocal===true) {
return;
} else {
event.preventDefault();
gtag('event', 'click', {
'event_category': 'outbound',
'event_label': window.location.href + ' --> ' + url,
'transport_type': 'beacon',
'event_callback': function(){element.unbind( "click"); element[0].click();}
});
}
}
I'm using the following code to load my Google Analytics (external javascript) in a way that is meant to not block rendering.
However, using both YSlow and Safari Web Inspector - the network traffic clearly shows that the ga.js script is still blocking rending.
/*
http://lyncd.com/2009/03/better-google-analytics-javascript/
Inserts GA using DOM insertion of <script> tag and "script onload" method to
initialize the pageTracker object. Prevents GA insertion from blocking I/O!
As suggested in Steve Souder's talk. See:
http://google-code-updates.blogspot.com/2009/03/steve-souders-lifes-too-short-write.html
*/
/* acct is GA account number, i.e. "UA-5555555-1" */
function gaSSDSLoad (acct) {
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
pageTracker,
s;
s = document.createElement('script');
s.src = gaJsHost + 'google-analytics.com/ga.js';
s.type = 'text/javascript';
s.onloadDone = false;
function init () {
pageTracker = _gat._getTracker(acct);
pageTracker._trackPageview();
}
s.onload = function () {
s.onloadDone = true;
init();
};
s.onreadystatechange = function() {
if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
s.onloadDone = true;
init();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
/* and run it */
gaSSDSLoad("UA-5555555-1");
Any ideas on how I can use JavaScript to delay the loading of the ga.js file, because the code above doesn't appear to do as it intends, until the entire page has been rendered so that I don't block rendering?
/* and run it */
gaSSDSLoad("UA-5555555-1");
Don't “run it” until the page has finished rendering. That is: onload or elsewhere further along. Don't include the above lines in your inline script block itself, or you won't gain anything.
If you use jQuery you can include the run it part in (which is the same as the body onLoad() event):
$(window).load(function() {
/* and run it */
gaSSDSLoad("UA-5555555-1");
});
and if that is not good enough, you run it a second later (for example...):
$(window).load(function() {
setTimeout("run_it()", 1000);
});
function run_it() {
/* and run it */
gaSSDSLoad("UA-5555555-1");
}
Shouldn´t be necessary though...
You can add a listener to the window, document or body's onload event and execute your gaSSDSLoad function at that time.
The code you get from Google Analytics is already non blocking.
Should be something like this:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5555555-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>
Google suggests to include it before the closing tag.
In general if you want to load other javascripts asyncronously I suggest you use some loader like:
LABjs
or ControlJS