JS uses Cookie to determine if a page is opened for the first time

  • 2020-12-16 05:51:25
  • OfStack

No more nonsense, directly to everyone posted the code, this article is not good also please forgive each hero.

JScript code:


function Cookie(key,value)
{
this.key=key;
if(value!=null)
{
this.value=escape(value);
}
this.expiresTime=null;
this.domain=null;
this.path="/";
this.secure=null;
}
Cookie.prototype.setValue=function(value){this.value=escape(value);}
Cookie.prototype.getValue=function(){return (this.value);}
Cookie.prototype.setExpiresTime=function(time){this.expiresTime=time;}
Cookie.prototype.getExpiresTime=function(){return this.expiresTime;}
Cookie.prototype.setDomain=function(domain){this.domain=domain;}
Cookie.prototype.getDomain=function(){return this.domain;}
Cookie.prototype.setPath=function(path){this.path=path;}
Cookie.prototype.getPath=function(){return this.path;}
Cookie.prototype.Write=function(v)
{
if(v!=null)
{
this.setValue(v);
}
var ck=this.key+"="+this.value;
if(this.expiresTime!=null)
{
try
{
ck+=";expires="+this.expiresTime.toUTCString();;
}
catch(err)
{
alert("expiresTime Parameter error ");
}
}
if(this.domain!=null)
{
ck+=";domain="+this.domain;
}
if(this.path!=null)
{
ck+=";path="+this.path;
}
if(this.secure!=null)
{
ck+=";secure";
}
document.cookie=ck;
}
Cookie.prototype.Read=function()
{
try
{
var cks=document.cookie.split("; ");
var i=0;
for(i=0;i <cks.length;i++)
{
var ck=cks[i];
var fields=ck.split("=");
if(fields[0]==this.key)
{
this.value=fields[1];
return (this.value);
}
}
return null;
}
catch(err)
{
alert("cookie Read error ");
return null;
}
}

HTML code:


<script type="text/javascript" src="Cookie.js"></script>
<script type="text/javascript" language="javascript">
window.onload=function(){
var ck=new Cookie("HasLoaded"); // Per-page new Cookie The name HasLoaded Not the same 
if(ck.Read()==null){// Unloaded, Cookie Content is empty 
alert(" First open page ");
// Set save time 
var dd = new Date();
dd = new Date(dd.getYear() + 1900, dd.getMonth(), dd.getDate());
dd.setDate(dd.getDate() + 365);
ck.setExpiresTime(dd);
ck.Write("true"); // Set up the Cookie . As long as IE Don't shut down, Cookie it 1 Straight there 
}
else{//Cookie Exists to indicate that the page is refreshed 
alert(" A page refresh ");
}
}
</script>

Above is the site to share JS by Cookie to determine whether the page is opened for the first time related content, hope to help you.


Related articles: