Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Last active February 19, 2022 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joduplessis/de5b2178fd2d2692a5cffa2a6492665e to your computer and use it in GitHub Desktop.
Save joduplessis/de5b2178fd2d2692a5cffa2a6492665e to your computer and use it in GitHub Desktop.
Simple session tracking using cookies only
window.addEventListener('load', function() {
function registerPageView(currentSessionCookieTimestamp) {
const currentTimestamp = new Date().getTime()
const fiveMinutes = 5 * 60 * 1000
if (!currentSessionCookieTimestamp) {
// ...PV logic...
} else {
if (currentTimestamp - currentSessionCookieTimestamp > fiveMinutes) {
// ...PV logic...
}
}
}
function getCookie() {
// the value being returned is the timestamp of when it was set
// stored as 'value' in setCookie() below
const name = 'COOKIE'
const value = '; ' + document.cookie
const parts = value.split('; ' + name + '=')
if (parts.length == 2) {
return parts
.pop()
.split(';')
.shift()
}
}
function setCookie() {
const name = 'COOKIE'
const value = new Date().getTime()
const date = new Date()
// Set it expire in 7 days
date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000)
document.cookie = name + '=' + value + '; expires=' + date.toUTCString() + '; path=/'
}
const currentSessionCookieTimestamp = getCookie()
const referrer = !!document.referrer ? document.referrer.split('/')[2] : ''
const { hostname } = location
// document.referrer approach ----------------------
if (referrer != hostname) registerPageView(currentSessionCookieTimestamp)
window.addEventListener('locationchange', () => setCookie())
// setInterval approach ---------------------------
registerPageView(currentSessionCookieTimestamp)
setInterval(() => setCookie(), 60000)
// Always set this on the first load no matter which approach
setCookie()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment