diff --git a/trafficSourceTracker.js b/trafficSourceTracker.js index b7dd3cb..f727490 100644 --- a/trafficSourceTracker.js +++ b/trafficSourceTracker.js @@ -1,22 +1,12 @@ -(function (window, document) -{ +/* +# Traffic Source Tracker - Google Analytics Last Non Direct Click Model +# Copyright (c) 2015, MarketLytics +# +# This project is free software, distributed under the MIT license. +# MarketLytics offers digital analytics consulting and integration services. +*/ +(function (window, document){ window.dataLayer=window.dataLayer||[]; - - -function splitHostname() { - var result = {}; - var regexParse = new RegExp('([a-z\-0-9]{2,63})\.([a-z\.]{2,5})$'); - var urlParts = regexParse.exec(window.location.hostname); - result.domain = urlParts[1]; - result.type = urlParts[2]; - //result.subdomain = window.location.hostname.replace(result.domain + '.' + result.type, '').slice(0, -1);; -//console.log(result.subdomain); - - return result; -} -var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; -//console.log(splitHostname().domain); - //including javascript in web page when JSON is undifined(first time), creating json source attribute, appending in head tag. if(typeof JSON === 'undefined') { var fileref = document.createElement('script'); @@ -29,8 +19,7 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; var cookieStrKey = 'traffic_src'; //inject global function for cookie retrieval. - var getTrafficSrcCookie = function() - { + window.getTrafficSrcCookie = function(){ var cookies = document.cookie.split(';'); var cookieObj; for(var i = 0; i < cookies.length; i++) { @@ -51,17 +40,16 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; var utils = { /*function is use to compare two parameters and return value if valid, *it looks for name(any variable) in url and returns its docoded value if found in url. - */ - getParameterByName: function(url, name) - { + */ + getParameterByName: function(url, name){ name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); var results = regex.exec(url); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }, - getKeywords: function(url) - { //return empty sting if url is empty or direct, which indicate no keywords used. + getKeywords: function(url){ + //return empty sting if url is empty or direct, which indicate no keywords used. if(url === '' || url === '(direct)') return ''; //we compare pre-define searchEngines object to find relavent keywords in url. @@ -79,8 +67,8 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; } } } - - //if url matches exact case of below regix we return not provided, which means campaign data is not present. + + //if url matches exact case of below regix we return not provided, which means campaign data is not present. var google = new RegExp('^https?:\/\/(www\.)?google(\.com?)?(\.[a-z]{2}t?)?\/?$', 'i'); var yahoo = new RegExp('^https?:\/\/(r\.)?search\.yahoo\.com\/?[^?]*$', 'i'); var bing = new RegExp('^https?:\/\/(www\.)?bing\.com\/?$', 'i'); @@ -92,8 +80,7 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; }, //function to set medium based on different params. - getMedium: function(ccokieObj) - { + getMedium: function(ccokieObj){ if(cookieObj.ga_medium !== '') return cookieObj.ga_medium; if(cookieObj.ga_gclid !== '') return 'cpc'; @@ -108,14 +95,12 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; }, //getting date and time for define number of years from today. - getDateAfterYears: function(years) - { + getDateAfterYears: function(years){ return new Date(new Date().getTime() + (years * 365 * 24 * 60 * 60 * 1000)); }, //checking url to return approprate hostname. - getHostname: function(url) - { + getHostname: function(url){ var re = new RegExp('^(https:\/\/|http:\/\/)?([^\/?:#]+)'); var match = re.exec(url)[2]; if(match !== null) { @@ -142,6 +127,20 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; }, 100); }; poll(); + }, + + removeSubdomain : function (host) { + var firstTLDs = "ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|be|bf|bg|bh|bi|bj|bm|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|cl|cm|cn|co|cr|cu|cv|cw|cx|cz|de|dj|dk|dm|do|dz|ec|ee|eg|es|et|eu|fi|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|im|in|io|iq|ir|is|it|je|jo|jp|kg|ki|km|kn|kp|kr|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|na|nc|ne|nf|ng|nl|no|nr|nu|nz|om|pa|pe|pf|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|yt".split('|'); + var secondTLDs = "com|edu|gov|net|mil|org|nom|sch|caa|res|off|gob|int|tur|ip6|uri|urn|asn|act|nsw|qld|tas|vic|pro|biz|adm|adv|agr|arq|art|ato|bio|bmd|cim|cng|cnt|ecn|eco|emp|eng|esp|etc|eti|far|fnd|fot|fst|g12|ggf|imb|ind|inf|jor|jus|leg|lel|mat|med|mus|not|ntr|odo|ppg|psc|psi|qsl|rec|slg|srv|teo|tmp|trd|vet|zlg|web|ltd|sld|pol|fin|k12|lib|pri|aip|fie|eun|sci|prd|cci|pvt|mod|idv|rel|sex|gen|nic|abr|bas|cal|cam|emr|fvg|laz|lig|lom|mar|mol|pmn|pug|sar|sic|taa|tos|umb|vao|vda|ven|mie|北海道|和歌山|神奈川|鹿児島|ass|rep|tra|per|ngo|soc|grp|plc|its|air|and|bus|can|ddr|jfk|mad|nrw|nyc|ski|spy|tcm|ulm|usa|war|fhs|vgs|dep|eid|fet|fla|flå|gol|hof|hol|sel|vik|cri|iwi|ing|abo|fam|gok|gon|gop|gos|aid|atm|gsm|sos|elk|waw|est|aca|bar|cpa|jur|law|sec|plo|www|bir|cbg|jar|khv|msk|nov|nsk|ptz|rnd|spb|stv|tom|tsk|udm|vrn|cmw|kms|nkz|snz|pub|fhv|red|ens|nat|rns|rnu|bbs|tel|bel|kep|nhs|dni|fed|isa|nsn|gub|e12|tec|орг|обр|упр|alt|nis|jpn|mex|ath|iki|nid|gda|inc".split('|'); + host = host.replace(/^www\./, ''); + var parts = host.split('.'); + while (parts.length > 3) { + parts.shift(); + } + if (parts.length === 3 && ((parts[1].length > 2 && parts[2].length > 2) || (secondTLDs.indexOf(parts[1]) === -1) && firstTLDs.indexOf(parts[2]) === -1)) { + parts.shift(); + } + return parts.join('.'); } }; @@ -177,8 +176,7 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; * function is used to save values in cookie defined above. */ - var setCookie = function(getGaClient) - { + var setCookie = function(getGaClient){ cookieObj.ga_gclid = utils.getParameterByName(document.location.href, 'gclid'); var ignoreUtmParameters = false; @@ -195,13 +193,11 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; } //source is assumed to be google when gclid is present and source is NULL - if (cookieObj.ga_gclid !== '' && cookieObj.ga_source === '') - { + if (cookieObj.ga_gclid !== '' && cookieObj.ga_source === ''){ cookieObj.ga_source = 'google'; } //Checks if ignoreUtmParameters is true. - else if(ignoreUtmParameters) - { + else if(ignoreUtmParameters){ //Checks is referrer exists. if(document.referrer.indexOf(document.location.host) >= 0) return; @@ -227,34 +223,38 @@ var rootDomain = '.' + splitHostname().domain + '.' + splitHostname().type; var cookieStr = JSON.stringify(cookieObj); //Creating cookie with expiry set for one year, can be accessed by function getTrafficSrcCookie(). document.cookie = cookieStrKey + '=; expires=' + new Date(-1); - document.cookie = cookieStrKey + '=' + cookieStr + '; expires=' + utils.getDateAfterYears(1)+'; domain='+rootDomain + '; path=/'; + document.cookie = cookieStrKey + '=' + cookieStr + '; expires=' + utils.getDateAfterYears(1) + '; path=/; domain=' + utils.removeSubdomain(location.hostname); } //Pushes event to dataLayer to prompt that cookies have been saved successfully. dataLayer.push({'event':'trafficSrcCookieSet'}) // Creates an event in jQuery on script ready. - // jQuery.event.trigger({ - // type: "Traffic_Source_Ready", - // message: "Traffic Source Ready", - // cookieData:getTrafficSrcCookie(), - // time: new Date() - // }); -document.addEventListener("name-of-event", function(e){ - //console.log(e.type); -}); - + if(jQuery){ + jQuery.event.trigger({ + type: "Traffic_Source_Ready_jQuery", + message: "Traffic Source Ready", + cookieData:getTrafficSrcCookie(), + time: new Date() + }); + } + if($){ + $.event.trigger({ + type: "Traffic_Source_Ready_$", + message: "Traffic Source Ready", + cookieData:getTrafficSrcCookie(), + time: new Date() + }); + } -// Create the event -var event = new CustomEvent("name-of-event", { - "type": "Traffic_Source_Ready", - message: "Traffic Source Ready", - cookieData:getTrafficSrcCookie(), - time: new Date() -}); + // Create the event + var event = new CustomEvent("Traffic_Source_Ready_Dom", { + type: "Traffic_Source_Ready", + message: "Traffic Source Ready", + cookieData:getTrafficSrcCookie(), + time: new Date() + }); -// Dispatch/Trigger/Fire the event -document.dispatchEvent(event); - - + // Dispatch/Trigger/Fire the event + document.dispatchEvent(event); cookieObj = {}; }; @@ -281,8 +281,6 @@ document.dispatchEvent(event); }); } - //Set the cookie by default can be overridden using setTrafficSrcCookie global function - // setTrafficSrcCookie(cookieObj) window.trafficSrcCookie = { setCookie: setTrafficSrcCookie,