>  기사  >  웹 프론트엔드  >  JS는 쿠키를 사용하여 페이지가 처음으로 열렸는지 확인합니다_javascript 기술

JS는 쿠키를 사용하여 페이지가 처음으로 열렸는지 확인합니다_javascript 기술

WBOY
WBOY원래의
2016-05-16 15:16:021886검색

더 이상 헛소리하지 마세요. 이 글이 잘 작성되지 않은 경우에는 코드만 게시하겠습니다.

JScript 코드:

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参数错误");
}
}
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读取错误");
return null;
}
}

HTML 코드:

<script type="text/javascript" src="Cookie.js"></script>
<script type="text/javascript" language="javascript">
window.onload=function(){
var ck=new Cookie("HasLoaded"); //每个页面的new Cookie名HasLoaded不能相同
if(ck.Read()==null){//未加载过,Cookie内容为空
alert("首次打开页面");
//设置保存时间
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"); //设置Cookie。只要IE不关闭,Cookie就一直存在
}
else{//Cookie存在,表示页面是被刷新的
alert("页面刷新");
}
}
</script>

위 내용은 JS가 쿠키를 사용하여 페이지가 처음 열렸는지 여부를 결정하는 것에 대해 편집자가 공유한 내용입니다. 모든 분들께 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.