Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Social Share Tracking With GA
// Track Facebook Likes
var fbCallback = function() {
FB.Event.subscribe('edge.create', function(targetUrl) {
ga('send', 'social', 'facebook', 'like', targetUrl);
});
}
if( window.fbAsyncInit ) {
fbCallback();
} else {
window.fbAsyncInit = fbCallback;
}
/* Track Social Sharing */
var socialShareUrls = {
"facebook" : {
"url" : "facebook.com/sharer/sharer.php",
"verb" : "share",
"captureQ" : "u"
},
"twitter" : {
"url" : "twitter.com/intent/tweet",
"verb" : "retweet",
"captureQ" : "url"
},
"pinterest": {
"url" : "pinterest.com/pin/create/bookmarklet",
"verb" : "pin",
"captureQ" : "url"
},
"linkedin" : {
"url" : "linkedin.com/shareArticle",
"verb" : "share",
"captureQ" : "url"
},
"buffer" : {
"url" : "buffer.com/add",
"verb" : "add",
"captureQ" : "url"
},
"digg" : {
"url" : "digg.com/submit",
"verb" : "submit",
"captureQ" : "url"
},
"tumblr" : {
"url" : "tumblr.com/widgets/share/tool",
"verb" : "share",
"captureQ" : "url"
},
"reddit" : {
"url" : "reddit.com/submit",
"verb" : "submit",
"captureQ" : "url"
},
"stumbleUpon" : {
"url" : "stumbleupon.com/submit",
"verb" : "submit",
"captureQ" : "url"
}
}
// Track each link if it matches social share url
var trackSocial = function( link ) {
for( socialSite in socialShareUrls ) {
var socialSiteData = socialShareUrls[socialSite];
if( link.indexOf( socialSiteData.url ) !== -1 ) {
var match = link.match( socialSiteData.captureQ + "=(http.*?(&|$))" );
ga('send', 'social', socialSite, socialSiteData.verb, match[1]);
}
}
};
function findParent(tagname,el) {
if ((el.nodeName || el.tagName).toLowerCase()===tagname.toLowerCase()){
return el;
}
while (el = el.parentNode){
if ((el.nodeName || el.tagName).toLowerCase()===tagname.toLowerCase()){
return el;
}
}
return null;
}
document.addEventListener('click', function(e){
// Find the nearest link where click originated.
// which contains sharer's URL
var parentLink = findParent("a", e.target);
if( parentLink.href ) {
trackSocial( parentLink.href );
}
});
// Take ownership of window.open to capture plugins which use it.
var oldWindowOpen = window.open;
window.open = function(){
trackSocial(arguments[0]);
oldWindowOpen.apply(this, arguments);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.