• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

javascript删除Cookie的正确方法(转载)

原来一直以为只要设置javascript的document.cookie对象就能简单的在浏览器端设置和删除cookie值,网上很多文章也是这么教的,但是最近发现简单的设置javascript的document.cookie的值无法完全做到删除或更改cookie。偶然发现了一篇文章给出了正确的方法,这里贴出来。

 

使用JavaScript清理Cookie首先要找到该Cookie对应的Name对应的值,然后设置其为过期:
找到Cookie有下面方法:

function getCookie2(name){
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));  
    if(arr != null) 
        return unescape(arr[2]); return null;
}

 

找到后设置为过期,切记设置domain和path,只有这两个参数跟你要删除的参数完全一样才能把它删除掉。

function resetNfluent(){
		alert("before=>"+document.cookie);
		var exp  = new Date();
		exp.setTime(exp.getTime() - 1);
		var cval=getCookie2('name');
		var lanObj=document.getElementById('lanOption');
		var lanSel=lanObj.value;
		alert(lanSel);
		if(lanSel=='en'){
			alert('let\'s reset nFluent');
			alert('cval=>'+cval);
			if(cval!=null){
				document.cookie="name="+cval+";domain=.example.com;expires="+exp.toGMTString()+";path=/";
			}else{
				document.cookie="name=;domain=.example.com;expires="+exp.toGMTString()+";path=/";
				}
		}else{
			alert('Don\'t need reset nFluent');
			}
		alert("after=>"+document.cookie);
    }

至于如何详细查看cookie的path和domain之类的东西,在firefox中可以根据以下步骤查看:
Tools->Option->Privacy->Show Cookie

 

原文地址

 

posted @ 2014-12-26 00:02  PowerCoder  阅读(12007)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3