javascript如何判断开启cookie和操作cookie代码详解

伊谢尔伦
伊谢尔伦原创
2017-07-25 15:19:291109浏览

判断是否开启cookie

<script>
 function checkCookie() {
  var result=false;
  if(navigator.cookiesEnabled){ return true; }
  document.cookie = "testcookie=yes;";
  
  var setCookie = document.cookie;
  
  if (setCookie.indexOf("testcookie=yes") > -1){
   result=true;
  }else{
   document.cookie = "";
  }
  
  return result;
 }
  
  if(!checkCookie()){
  alert("对不起,您的浏览器的Cookie功能被禁用,请开启"); 
  }else{
  alert("Cookie 成功开启");
  }
</script>

操作cookie

// 1. 设置COOKIE
  
// 简单型
  
function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
  
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
  
// 完整型
function SetCookie(name,value,expires,path,domain,secure)
{
var expDays = expires*24*60*60*1000;
  
var expDate = new Date();
expDate.setTime(expDate.getTime()+expDays);
  
var expString = ((expires==null) ? "" : (";expires=”+expDate.toGMTString()))
var pathString = ((path==null) ? "" : (";path="+path))
var domainString = ((domain==null) ? "" : (";domain="+domain))
var secureString = ((secure==true) ? ";secure" : "" )
document.cookie = name + "=" + escape(value) + expString + pathString + domainString + secureString;
}
  
  
// 2.获取指定名称的cookie值:
  
function getCookie(c_name)
{
if (document.cookie.length>0)
 {
 c_start=document.cookie.indexOf(c_name + "=")
 if (c_start!=-1)
 {
 c_start=c_start + c_name.length+1
 c_end=document.cookie.indexOf(";",c_start)
 if (c_end==-1) c_end=document.cookie.length
 return unescape(document.cookie.substring(c_start,c_end))
 }
 }
return ""
}
  
  
// 3.删除指定名称的cookie:
  
function ClearCookie(name)
{
var expDate = new Date();
expDate.setTime(expDate.getTime()-100);
  
document.cookie=name+”=;expires=”+expDate.toGMTString();
  
}
  
// 4. 检测cookie:
  
function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
 {alert('Welcome again '+username+'!')}
else
 {
 username=prompt('Please enter your name:',"")
 if (username!=null && username!="")
 {
 setCookie('username',username,365)
 }
 }
}

以上就是javascript如何判断开启cookie和操作cookie代码详解的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。