Skip to content

Instantly share code, notes, and snippets.

@sperand-io
Created April 18, 2016 09:44
Show Gist options
  • Save sperand-io/e1afb171485be3405d5bd4819faa7fbc to your computer and use it in GitHub Desktop.
Save sperand-io/e1afb171485be3405d5bd4819faa7fbc to your computer and use it in GitHub Desktop.
// analytics.page('Name', { returning: getNewOrRepeat() === 'repeat' })
function getNewOrRepeat() {
var session = 30; // minutes — feel free to change
var timeout = 30; // days — feel free to change
var cookie = '__nr' // cookie name — feel free to change
var now = new Date().getTime();
var day = 24 * 60 * 60 * 1000;
var minute = 60 * 1000;
var expires = new Date(new Date().setTime(now + timeout * day)).toUTCString();
var cookieValue = getCookieValue(cookie);
if (cookieValue) {
var parts = cookieValue.split('-');
return now - parts[0] < session * minute && parts[1] == 'new'
? saveAndReturn('new')
: saveAndReturn('repeat');
}
return saveAndReturn('new');
function saveAndReturn(state) {
document.cookie = cookie +'='+ now +'-'+ state + '; expires=' + expires;
return state;
}
function getCookieValue(cookie) {
var pairs = document.cookie.split(/ *; */);
if ('' === pairs[0]) return '';
for (var i = 0; i < pairs.length; ++i) {
var parts = pairs[i].split('=');
if (parts[0] !== cookie) continue;
return parts[1];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment