开发者

Deleting a cookie in Javascript does not work consistently

I have the following code to set, get, and delete cookies:

function set_cookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );

  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( 开发者_Python百科( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function get_cookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) &&
     ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function delete_cookie(name) {
    document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}

In my program, I have something called an active message and use a cookie to remember the path and existence of the active message. Naturally I have a discard message function that will delete the cookie. It looks like this:

function discard_message() {
    alert('cookie = '+get_cookie('active_message'));
    clear_active_message_cookie();
    alert('should be null = '+get_cookie('active_message'));
    update_message('Discard', false, false);    
}

function clear_active_message_cookie(){
    delete_cookie("active_message");
}

As you can see I have put alerts in to check if the cookie is readable after deleting it. The odd thing is that in one part of my application the cookie deletes successfully, but discarding a message in another part of my application does not work. The second cookie alert prints the value of the cookie. I have confirmed the name of the cookie is the same.

It is almost like my request to delete a cookie is getting denied. Does anyone know in what circumstances this is possible?

Thanks!


I think a deleted cookie will only be de-actived after you have navigated away from the current page.

Insert the code below right after you delete the cookie;

location.href="bringmeback.html";

bringmeback.html (redirect to current page);

location.href="currentpage.html";

You can use this code to test if your cookie was completely deleted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜