Skip to content

Instantly share code, notes, and snippets.

@ju1
Created June 10, 2018 20:44
Show Gist options
  • Save ju1/5015ab5703d30d58589193fd4313e7b8 to your computer and use it in GitHub Desktop.
Save ju1/5015ab5703d30d58589193fd4313e7b8 to your computer and use it in GitHub Desktop.
Pageview Count Stored in the Cookie
<script>function setCookie(name, value, expires) {
var cookie = name + "=" + value + "; path=/; domain=." + location.hostname.replace(/^www\./i, "");
if (typeof expires !== "undefined") {
var now = new Date();
now.setTime(now.getTime() + expires * 24 * 60 * 60 * 1000);
cookie += "; expires=" + now.toUTCString();
}
document.cookie = cookie;
}
function getCookie(name) {
var cookies = document.cookie.split(";"),
toReturn;
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.indexOf(name + "=") === 0) {
toReturn = cookie.substring((name + "=").length, cookie.length);
}
}
return toReturn;
}
(function() {
var pageviewCount = getCookie("pageviewCount");
if (typeof pageviewCount === "undefined") {
pageviewCount = 1;
} else {
pageviewCount++;
}
setCookie("pageviewCount", pageviewCount, 30);
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment