2

在客户端上运行时如何删除 dart 中的 cookie?

我试图通过使用将其设置为空字符串来删除它

document.cookie = 'cookie_to_be_deleted=""';

如果我在这一行之后打印 cookie 的值,我会得到一个以分号分隔的键值对列表,其中包含两个“cookie_to_be_deleted”实例。一个有我希望删除的原始值,另一个有一个空字符串作为它的值。

4

1 回答 1

7

尝试这个:

Date then = new Date.fromEpoch(0, new TimeZone.utc());
document.cookie = 'cookie_to_be_deleted=; expires=' + then.toString() + '; path=/';

在https://gist.github.com/d2m/1935339找到这些实用程序

/* 
 * dart document.cookie lib
 *
 * ported from
 * http://www.quirksmode.org/js/cookies.html
 *
 */

void createCookie(String name, String value, int days) {
  String expires;
  if (days != null)  {
    Date now = new Date.now();
    Date date = new Date.fromEpoch(now.value + days*24*60*60*1000, new TimeZone.local());
    expires = '; expires=' + date.toString();    
  } else {
    Date then = new Date.fromEpoch(0, new TimeZone.utc());
    expires = '; expires=' + then.toString();
  }
  document.cookie = name + '=' + value + expires + '; path=/';
}

String readCookie(String name) {
  String nameEQ = name + '=';
  List<String> ca = document.cookie.split(';');
  for (int i = 0; i < ca.length; i++) {
    String c = ca[i];
    c = c.trim();
    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length);
    }
  }
  return null;  
}

void eraseCookie(String name) {
  createCookie(name, '', null);
}
于 2013-08-28T19:47:44.990 回答