saving first visit data in a cookie

<!-- First Visit cookie tag-->
<script type="text/Javascript">

// Helper functions
//
//

function writeCookie(name, value, days){
  // By default there is no expiration so the cookie is set to temporary
  var expires = "";
  
  // Specifying a number of days makes the cookie persistent
  if (days){
    var date = new Date();
	date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
	expires = "; expires=" + date.toString();
  }
  
  // Set the cookie to the name, value, and expiration date
  // edit the path so this is only applicable on the desired domain
  // ";path=/;domain=.seniors.com.au"
  document.cookie = name + "=" + value + expires;  
}

function readCookie(name){
  // Find the specified cookie and return its value
  var searchName = name+ "=";
  var cookies = document.cookie.split(';');
  
  for(var i = 0; i < cookies.length; i++){
    var c = cookies[i];
	while (c.charAt(0) == ' '){
	  c = c.substring(1, c.length);
	}
	if (c.indexOf(searchName) == 0){
	  return c.substring(searchName.length, c.length);
	}
  }
  return null;
}

function eraseCookie(name){
  // Erase the specified cookie
  writeCookie(name, "", -1);
}

function makeCookies(){
  // make the stasis cookies
  writeCookie("__first_visit_time", firstVisitTime, 30);
  writeCookie("__first_referrer", firstReferrer, 30);
  writeCookie("__first_landing_url", firstLandingURL, 30);
  writeCookie("__last_update_date", lastUpdateDate, 30);
}

// cookie names
// __first_visit_time
// __first_referrer
// __first_landing_url
// __last_update_date


var lastUpdateDate = readCookie("__last_update_date")

var today = new Date();
today = today.toDateString();

if (lastUpdateDate){
  if (lastUpdateDate != today){
    var firstReferrer = readCookie("__first_referrer");
    var firstLandingURL = readCookie("__first_landing_url");
    var firstVisitTime = readCookie("__first_visit_time");
    
    makeCookies();
  }

}
else {
  var firstVisitTime = new Date();
  firstVisitTime = firstVisitTime.toString();
  
  var firstReferrer = document.referrer;
  // if the referrer is an empty string
  if (firstReferrer == ""){
    firstReferrer = "___";
  }
  
  var firstLandingURL = document.URL;

  lastUpdateDate = new Date();
  lastUpdateDate = lastUpdateDate.toDateString();
  
  makeCookies();
}

</script>

Send a Comment

Your email address will not be published.