Skip to content

Instantly share code, notes, and snippets.

@pualien
Created November 8, 2019 16:10
Show Gist options
  • Save pualien/cf831848de1d5060069f83fcd86677c1 to your computer and use it in GitHub Desktop.
Save pualien/cf831848de1d5060069f83fcd86677c1 to your computer and use it in GitHub Desktop.
JS to retrieve Traffic Data Sources without Google Analytics Cookies
var __firstSessionCookieName = '$$FIRST_SESSION_COOKIE_NAME$$';
var __returningSessionCookieName = '$$RETURNING_SESSION_COOKIE_NAME$$';
var __cookieExpiration = '$$COOKIE_GMT_EXPIRATION$$';
var __reviveFirstSession = true; //Revive first session and avoids saving returning session
var __customCampaignParam = '$$CUSTOM_CAMPAIGN_QUERY_PARAM$$';
function __crumbleCookie(a) {
for (var d = document.cookie.split(";"), c = {}, b = 0; b < d.length; b++) {
var e = d[b].substring(0, d[b].indexOf("=")).trim();
c[e] = d[b].substring(d[b].indexOf("=") + 1, d[b].length).trim()
}
if (a && c[a]) {
var ret_obj = {};
for (var i = 0; i < c[a].split('$').length; i++) {
if (c[a].split("$")[i].split(':').length === 2) {
if (c[a].split("$")[i].split(':')[1]) {
ret_obj[c[a].split("$")[i].split(':')[0]] = c[a].split("$")[i].split(':')[1];
}
}
}
return ret_obj
}
return undefined;
}
function __bakeCookie(a, d, c, b, e, i) {
document.cookie = a + "=" + d + (c ? ";expires=" + c : "") + (b ? ";path=" + b : "") + (e ? ";domain=" + e : "") + (i ? ";secure" : "")
}
function __writeLogic(n, __reviveFirstSession) {
var a = __getTrafficSource(__reviveFirstSession);
a = a.replace(/\|{2,}/g, "|");
a = a.replace(/^\|/, "");
a = unescape(a);
__bakeCookie(n, a, __cookieExpiration, "/", "", "")
}
function __getParam(s, q) {
try {
var match = s.match('[?&]' + q + '=([^&]+)');
return match ? match[1] : '';
} catch (e) {
return '';
}
}
function __calculateTrafficSource() {
var source = '', medium = '', campaign = '', term = '', content = '';
var search_engines = [['bing', 'q'], ['google', 'q'], ['yahoo', 'q'], ['baidu', 'q'], ['yandex', 'q'], ['ask', 'q']]; //List of search engines names and search terms
var social_providers = [['twitter', 't.co'], ['facebook', 'facebook.com'], ['youtube', 'youtube.com']]; //List of social providers names and domains
var ref = document.referrer;
ref = ref.substr(ref.indexOf('//') + 2);
ref_domain = ref;
ref_path = '/';
ref_search = '';
// Checks for campaign parameters
var url_search = document.location.search;
if (url_search.indexOf('utm_source') > -1) {
source = __getParam(url_search, 'utm_source');
medium = __getParam(url_search, 'utm_medium');
campaign = __getParam(url_search, 'utm_campaign');
term = __getParam(url_search, 'utm_term');
content = __getParam(url_search, 'utm_content');
} else if (__getParam(url_search, 'gclid')) {
source = 'google';
medium = 'cpc';
campaign = '(not set)';
} else if (__getParam(url_search, 'fbclid')) {
source = 'facebook';
medium = 'social';
campaign = '(not set)';
} else if (ref) {
// separate domain, path and query parameters
if (ref.indexOf('/') > -1) {
ref_domain = ref.substr(0, ref.indexOf('/'));
ref_path = ref.substr(ref.indexOf('/'));
if (ref_path.indexOf('?') > -1) {
ref_search = ref_path.substr(ref_path.indexOf('?') + 1);
ref_path = ref_path.substr(0, ref_path.indexOf('?'));
}
}
medium = 'referral';
source = ref_domain;
// Extract term for organic source
for (var i = 0; i < search_engines.length; i++) {
if (ref_domain.indexOf(search_engines[i][0]) > -1) {
medium = 'organic';
source = search_engines[i][0];
term = __getParam(ref_search, search_engines[i][1]) || '(not provided)';
break;
}
}
for (var j = 0; j < social_providers.length; j++) {
if (ref_domain.indexOf(social_providers[j][1]) > -1) {
medium = 'social';
source = social_providers[j][0];
break;
}
}
}
if (__customCampaignParam && __customCampaignParam.length) {
campaign = campaign.length ? campaign : unescape(__getParam(url_search, __customCampaignParam));
}
return {
'source': source,
'medium': medium,
'campaign': campaign,
'term': term,
'content': content
};
}
function __getTrafficSource(__reviveFirstSession) {
var trafficSources = {};
if (__reviveFirstSession && __reviveFirstSession === true) {
trafficSources = __crumbleCookie(__firstSessionCookieName);
} else {
trafficSources = __calculateTrafficSource();
}
var source = trafficSources.source.length === 0 ? 'direct' : trafficSources.source;
var medium = trafficSources.medium.length === 0 ? 'none' : trafficSources.medium;
var campaign = trafficSources.campaign.length === 0 ? 'direct' : trafficSources.campaign;
// exception
// if (medium === 'referral') {
// campaign = '';
// }
var rightNow = new Date();
return 'source:' + source +
'$medium:' + medium +
'$campaign:' + campaign +
'$term:' + trafficSources.term +
'$content:' + trafficSources.content +
'$date:' + rightNow.toISOString().slice(0, 10).replace(/-/g, "");
}
function __getTrafficSourceFromCookies() {
function isEmpty(obj) {
if (typeof obj === 'object' && obj !== null) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
} else {
return true;
}
}
return __crumbleCookie(__returningSessionCookieName) && !isEmpty(__crumbleCookie(__returningSessionCookieName)) ? __crumbleCookie(__returningSessionCookieName) : __crumbleCookie(__firstSessionCookieName);
}
(function () {
if (__firstSessionCookieName && __firstSessionCookieName.length) {
var session = __crumbleCookie(__firstSessionCookieName);
if (typeof session == 'undefined') // First time session
{
// first session
__writeLogic(__firstSessionCookieName);
} else {
if (__reviveFirstSession && __reviveFirstSession === true) {
// revive first session
__writeLogic(__firstSessionCookieName, __reviveFirstSession);
} else {
// returning session
if (__returningSessionCookieName && __returningSessionCookieName.length) {
__writeLogic(__returningSessionCookieName);
}
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment