转:JS通过Cookie判断页面是否为首次打开
JScript code:
1 function Cookie(key,value){ 2 this.key=key; 3 if(value!=null){ 4 this.value=escape(value); 5 } 6 this.expiresTime=null; 7 this.domain=null; 8 this.path="/"; 9 this.secure=null; 10 } 11 Cookie.prototype.setValue=function(value){this.value=escape(value);} 12 Cookie.prototype.getValue=function(){return (this.value);} 13 Cookie.prototype.setExpiresTime=function(time){this.expiresTime=time;} 14 Cookie.prototype.getExpiresTime=function(){return this.expiresTime;} 15 Cookie.prototype.setDomain=function(domain){this.domain=domain;} 16 Cookie.prototype.getDomain=function(){return this.domain;} 17 Cookie.prototype.setPath=function(path){this.path=path;} 18 Cookie.prototype.getPath=function(){return this.path;} 19 Cookie.prototype.Write=function(v){ 20 if(v!=null){ 21 this.setValue(v); 22 } 23 var ck=this.key+"="+this.value; 24 if(this.expiresTime!=null){ 25 try{ 26 ck+=";expires="+this.expiresTime.toUTCString();; 27 }catch(err){ 28 alert("expiresTime参数错误"); 29 } 30 } 31 if(this.domain!=null){ 32 ck+=";domain="+this.domain; 33 } 34 if(this.path!=null){ 35 ck+=";path="+this.path; 36 } 37 if(this.secure!=null){ 38 ck+=";secure"; 39 } 40 document.cookie=ck; 41 } 42 Cookie.prototype.Read=function(){ 43 try{ 44 var cks=document.cookie.split("; "); 45 var i=0; 46 for(i=0;i <cks.length;i++){ 47 var ck=cks[i]; 48 var fields=ck.split("="); 49 if(fields[0]==this.key){ 50 this.value=fields[1]; 51 return (this.value); 52 } 53 } 54 return null; 55 }catch(err){ 56 alert("cookie读取错误"); 57 return null; 58 } 59 }
HTML code:
1 <script type="text/javascript" src="Cookie.js"></script> 2 <script type="text/javascript" language="javascript"> 3 window.onload=function(){ 4 var ck=new Cookie("HasLoaded"); //每个页面的new Cookie名HasLoaded不能相同 5 if(ck.Read()==null){//未加载过,Cookie内容为空 6 alert("首次打开页面"); 7 //设置保存时间 8 var dd = new Date(); 9 dd = new Date(dd.getYear() + 1900, dd.getMonth(), dd.getDate(), dd.getHours(), dd.getMinutes(), dd.getSeconds()); 10 dd.setSeconds(dd.getSeconds() + 10); 11 ck.setExpiresTime(dd); 12 ck.Write("true"); //设置Cookie。只要IE不关闭,Cookie就一直存在 13 }else{//Cookie存在,表示页面是被刷新的 14 alert("页面刷新"); 15 } 16 } 17 </script>
转载自:https://www.jb51.net/article/79234.htm
时间上有改动,即
dd = new Date(dd.getYear() + 1900, dd.getMonth(), dd.getDate(), dd.getHours(), dd.getMinutes(), dd.getSeconds()); dd.setSeconds(dd.getSeconds() + 10);
此处我设置了秒,容易看清楚效果,如果改成分钟、小时或天,则改为如下所示:
dd.setMinutes(dd.getMinutes() + 5); //cookie保存5分钟
dd.setHours(dd.getHours() + 2); //cookie保存2小时
dd.setDate(dd.getDate() + 1); //cookie保存1小时