如何删除Dart中的cookie

时间:2013-08-28 16:40:43

标签: cookies dart

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

我试图通过使用

将其设置为空字符串来删除它
document.cookie = 'cookie_to_be_deleted=""';

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

1 个答案:

答案 0 :(得分: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);
}