Detect New Website Visitors with JavaScript Cookie

Sometimes it might want to show a custom message to new visitors, such as a cookie warning or some other custom content. Even our online HTML editor is detecting returning visitors and doesn’t show the demo content to them. This lightweight JavaScript solution will help you detect returning visitors with the use of a cookie.
detect first visitor cookie javascript

Live demo

Open the live demo and refresh the page to see the message changing. Refresh the page to get something else the second time. Use the Chrome Web Developer browser extension to erase the cookies and make the website behave like you’re a first time visitor.

The Script

The JavaScript barely 30 lines long uncompressed. You’ll have to customize it according to your needs. Change what happens with new and with returning visitors. In this demo it just changes the contents of a DOM element (#firstVisit).

function GetCookie(name) {
  var arg=name+"=";
  var alen=arg.length;
  var clen=document.cookie.length;
  var i=0;
  while (i<clen) {
	var j=i+alen;
	if (document.cookie.substring(i,j)==arg)
	  return "here";
	i=document.cookie.indexOf(" ",i)+1;
	if (i==0) break;
  }
  return null;
}
function testFirstCookie(){
	var visit=GetCookie("FirstTimeVisitCookie");
	if (visit==null){
	   var expire=new Date();
	   expire=new Date(expire.getTime()+7776000000);
	   document.cookie="FirstTimeVisitCookie=here; expires="+expire;
	   document.getElementById("firstVisit").innerHTML = "Welcome! You are here for the first time!";	// New visitor
   } else {
	   document.getElementById("firstVisit").innerHTML = "Welcome back!";	// Returning visitor
   }
}
$(document).ready(function(){
	testFirstCookie();
});