Skip to content

Instantly share code, notes, and snippets.

@wrburgess
Created March 9, 2012 06:24
Show Gist options
  • Save wrburgess/2005331 to your computer and use it in GitHub Desktop.
Save wrburgess/2005331 to your computer and use it in GitHub Desktop.
Tracking Facebook and Twitter Events with Google Analytics #googleanalytics #social #facebook #twitter
For more info:
http://code.google.com/apis/analytics/docs/tracking/gaTrackingSocial.html
http://www.socialmediaexaminer.com/how-to-track-tweets-facebook-likes-and-more-with-google-analytics/
Place between <head></head> tags:
<head>
<meta charset="utf-8" />
<title>Example Page</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1" />
<meta name="description" content="3M Mobile Racing" />
<link rel="stylesheet" href="/css/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29223617-7']);
_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 src="/js/ga_social_tracking.js"></script>
<script>
(function(){
var twitterWidgets = document.createElement('script');
twitterWidgets.type = 'text/javascript';
twitterWidgets.async = true;
twitterWidgets.src = 'http://platform.twitter.com/widgets.js';
// Setup a callback to track once the script loads.
twitterWidgets.onload = _ga.trackTwitter;
document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
})();
</script>
</head>
Place after <body> tag:
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=178146448912285";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
Place in document body:
<div id="facebook-like">
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script type="text/javascript">_ga.trackFacebook();</script>
<fb:like href="www.example.com/example" send="true" width="450" show_faces="false" font=""></fb:like>
</div>
<div id="twitter-tweet">
<a href="https://twitter.com/share" class="twitter-share-button">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
Place in js file:
referenced above at <script src="/js/ga_social_tracking.js"></script>
// Copyright 2011 Google Inc. All Rights Reserved.
/**
* @fileoverview A simple script to automatically track Facebook and Twitter
* buttons using Google Analytics social tracking feature.
* @author [email protected] (Nick Mihailovski)
*/
/**
* Namespace.
* @type {Object}.
*/
var _ga = _ga || {};
/**
* Ensure global _gaq Google Anlaytics queue has be initialized.
* @type {Array}
*/
var _gaq = _gaq || [];
/**
* Helper method to track social features. This assumes all the social
* scripts / apis are loaded synchronously. If they are loaded async,
* you might need to add the nextwork specific tracking call to the
* a callback once the network's script has loaded.
* @param {string} opt_pageUrl An optional URL to associate the social
* tracking with a particular page.
* @param {string} opt_trackerName An optional name for the tracker object.
*/
_ga.trackSocial = function(opt_pageUrl, opt_trackerName) {
_ga.trackFacebook(opt_pageUrl, opt_trackerName);
_ga.trackTwitter(opt_pageUrl, opt_trackerName);
};
/**
* Tracks Facebook likes, unlikes and sends by suscribing to the Facebook
* JSAPI event model. Note: This will not track facebook buttons using the
* iFrame method.
* @param {string} opt_pageUrl An optional URL to associate the social
* tracking with a particular page.
* @param {string} opt_trackerName An optional name for the tracker object.
*/
_ga.trackFacebook = function(opt_pageUrl, opt_trackerName) {
var trackerName = _ga.buildTrackerName_(opt_trackerName);
try {
if (FB && FB.Event && FB.Event.subscribe) {
FB.Event.subscribe('edge.create', function(targetUrl) {
_gaq.push([trackerName + '_trackSocial', 'facebook', 'like',
targetUrl, opt_pageUrl]);
});
FB.Event.subscribe('edge.remove', function(targetUrl) {
_gaq.push([trackerName + '_trackSocial', 'facebook', 'unlike',
targetUrl, opt_pageUrl]);
});
FB.Event.subscribe('message.send', function(targetUrl) {
_gaq.push([trackerName + '_trackSocial', 'facebook', 'send',
targetUrl, opt_pageUrl]);
});
/* Comment tracking from the tucknott.net blog */
FB.Event.subscribe('comment.create', function(targetUrl) {
_gaq.push(['_trackSocial', 'facebook', 'comment', targetUrl]);
});
FB.Event.subscribe('comment.remove', function(targetUrl) {
_gaq.push(['_trackSocial', 'facebook', 'uncomment', targetUrl]);
});
}
} catch (e) {}
};
/**
* Returns the normalized tracker name configuration parameter.
* @param {string} opt_trackerName An optional name for the tracker object.
* @return {string} If opt_trackerName is set, then the value appended with
* a . Otherwise an empty string.
* @private
*/
_ga.buildTrackerName_ = function(opt_trackerName) {
return opt_trackerName ? opt_trackerName + '.' : '';
};
/**
* Tracks everytime a user clicks on a tweet button from Twitter.
* This subscribes to the Twitter JS API event mechanism to listen for
* clicks coming from this page. Details here:
* http://dev.twitter.com/pages/intents-events#click
* This method should be called once the twitter API has loaded.
* @param {string} opt_pageUrl An optional URL to associate the social
* tracking with a particular page.
* @param {string} opt_trackerName An optional name for the tracker object.
*/
_ga.trackTwitter = function(opt_pageUrl, opt_trackerName) {
var trackerName = _ga.buildTrackerName_(opt_trackerName);
try {
if (twttr && twttr.events && twttr.events.bind) {
twttr.events.bind('tweet', function(event) {
if (event) {
var targetUrl; // Default value is undefined.
if (event.target && event.target.nodeName == 'IFRAME') {
targetUrl = _ga.extractParamFromUri_(event.target.src, 'url');
}
_gaq.push([trackerName + '_trackSocial', 'twitter', 'tweet',
targetUrl, opt_pageUrl]);
}
});
}
} catch (e) {}
};
/**
* Extracts a query parameter value from a URI.
* @param {string} uri The URI from which to extract the parameter.
* @param {string} paramName The name of the query paramater to extract.
* @return {string} The un-encoded value of the query paramater. underfined
* if there is no URI parameter.
* @private
*/
_ga.extractParamFromUri_ = function(uri, paramName) {
if (!uri) {
return;
}
var uri = uri.split('#')[0]; // Remove anchor.
var parts = uri.split('?'); // Check for query params.
if (parts.length == 1) {
return;
}
var query = decodeURI(parts[1]);
// Find url param.
paramName += '=';
var params = query.split('&');
for (var i = 0, param; param = params[i]; ++i) {
if (param.indexOf(paramName) === 0) {
return unescape(param.split('=')[1]);
}
}
return;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment