Skip to content

Instantly share code, notes, and snippets.

@kitwalker12
Created November 13, 2013 01:59
Show Gist options
  • Select an option

  • Save kitwalker12/7442291 to your computer and use it in GitHub Desktop.

Select an option

Save kitwalker12/7442291 to your computer and use it in GitHub Desktop.
Set cookies based on referral links
// init namespace
window.app = {};
window.app.custom = {};
(function ($, app) {
var $window = $(window);
app.captureCampaign = {
parameters: ['campaign_source'],
cookiePersistDays: 30,
cookiePath: '',
cookieDomain: "." + window.location.hostname,
cookieSecure: false,
getParameterByName: function(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results === null) {
return "";
} else {
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
},
readCookie: function(name) {
var name = name + "=";
var cookieArray = document.cookie.split(';');
for (var i = cookieArray.length - 1; i >= 0; i--) {
var c = cookieArray[i];
while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
if (c.indexOf(name) === 0) { return c.substring(name.length, c.length);}
};
},
createCookie: function(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
var cookie_string = name + "=" + value + expires;
cookie_string += "; domain=" + (this.cookieDomain.length ? this.cookieDomain : window.location.hostname);
cookie_string += "; path=" + (this.cookiePath.length ? this.cookiePath : '/');
if (this.cookieSecure) {
cookie_string += "; secure";
}
document.cookie = cookie_string;
},
capture: function() { //Run through parameters array and set cookies for all identified URL parameters
for (var i = this.parameters.length - 1; i >= 0; i--) {
parameter = this.parameters[i];
var value = this.getParameterByName(parameter);
if ( value !== null && value !== "") {
this.createCookie(parameter, "", -1);
this.createCookie(parameter, value, this.cookiePersistDays);
}
};
},
set: function(name, value) { //Manually set cookie
if (name !== null && name !== "" && value !== null && value !== "") {
this.createCookie(name, "", -1);
this.createCookie(name, value, this.cookiePersistDays);
}
}
}
$(document).ready(function() {
//Cookie Handler
app.captureCampaign.parameters = ['campaign_source', 'campaign_term']
app.captureCampaign.capture();
});
}(jQuery, app.custom));
@Ojay

Ojay commented Jul 9, 2014

Copy link
Copy Markdown

This looks really intriguing...
What would an example referral link look like? I'm struggling to work it out. Thanks for any advice :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment