通过Javascript删除或重置浏览器cookie

时间:2011-04-12 15:47:57

标签: javascript cookies

HTML链接:

<a href="javascript:del_cookie(name);">Logout</a>
<a href="javascript:delete_cookie(rememberKeepMeLoggedIn);">Logout</a>
<a href="javascript:eraseCookie(name);">Logout</a>

<a href="#" onclick="del_cookie(name);">Logout</a>
<a href="#" onclick="delete_cookie(rememberKeepMeLoggedIn);">Logout</a>
<a href="#" onclick="eraseCookie(name);">Logout</a>

Javascript:

  

function delete_cookie(rememberKeepMeLoggedIn){
    var cookie_date = new Date();
    cookie_date.setTime(cookie_date.getTime() - 1);
    document.cookie = rememberKeepMeLoggedIn + =“=; expires =”+ cookie_date.toGMTString();
  }

     

function del_cookie(name){   document.cookie ='acceptsCookies =; expires = Thu,1970年1月1日00:00:00 GMT;';
window.location =“http://www.smugmug.com/logout.mg?goTo=#
  }

     

function eraseCookie(name){   var cookies = document.cookie.split(“;”);
  for(var i = 0; i&lt; cookies.length; i ++)
  eraseCookies(饼干[I] .split( “=”)[0]);
  }

如何删除或重置名为“UP-759283”的Cookie? 下面的语法看起来不错吗?

这是我的javascript函数:

  

function del_cookie(){
  document.cookie = UP-759283 +'=; expires =星期四,01-Jan-70 00:00:01 GMT;';
  }

HTML网址标注
<a href="javascript:del_cookie(); document.location.reload( );">Logout</a>

1 个答案:

答案 0 :(得分:3)

  

下面的语法看起来不错吗?

没有;只需通过JSLint运行您的代码,您就会看到。改变

document.cookie = UP-759283 +'=; expires=Thu, 01-Jan-70 00:00:01 GMT;'; 

document.cookie = 'UP-759283=; expires=Thu, 01-Jan-70 00:00:01 GMT;'; 

根据MDC document.cookie docs,通过将到期时间设置为零来删除cookie:

document.cookie = 'UP-759283=; expires=Thu, 01 Jan 1970 00:00:00 GMT;';

其他参考:cookies @ quirksmode