How I can delete cookies in Dart?

1,605 views
Skip to first unread message

Timur

unread,
Feb 28, 2012, 4:17:33 AM2/28/12
to General Dart Discussion
Hi all,
How I can delete cookies?
I've tried to do this: document.cookie = '';
but cookie still there...
thanks

Michael Haubenwallner

unread,
Feb 28, 2012, 4:43:48 PM2/28/12
to General Dart Discussion
I've put up a gist for your pleasure at https://gist.github.com/1935339

Артур Файзрахманов

unread,
Aug 2, 2013, 9:14:34 AM8/2/13
to mi...@dartlang.org
Here is a bit different approach
https://groups.google.com/a/dartlang.org/forum/#!topic/misc/XDafaSKOCVE

вторник, 28 февраля 2012 г., 15:17:33 UTC+6 пользователь Timur написал:

Артур Файзрахманов

unread,
Aug 2, 2013, 3:17:35 PM8/2/13
to mi...@dartlang.org
I've tried to use that solutions for myself and found out that some things changed, here is my approach:

class Month {

  static const List<String> short3l = const ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  static String getShort(num i) => Month.short3l[i-1];

}


class ClientCookie{

  static Map _readCookie(){

    var cookie = new Map();

    document.cookie.split(';').forEach((e){

      var k = e.indexOf('=');

      if(k > 0){

        cookie[Uri.decodeComponent(e.substring(0, k))] = Uri.decodeComponent(e.substring(k + 1));

      }

    });

    return cookie;

  }


  static _writeCookie(Map m){

    String sc = '';

    m.forEach((String k, v) {

        sc = '$sc''$k=$v;';

    });

    document.cookie = sc;

  }


  static void setCookie(String name, Object value, { int ms : null }){

    var m = new Map();

    m[name] = value.toString();

    if(ms != null){

      DateTime t = new DateTime.fromMillisecondsSinceEpoch(new DateTime.now().millisecondsSinceEpoch + ms);

      m['expires'] = '${t.day}-${Month.getShort(t.month)}-${t.year} ${t.hour}:${t.minute}:${t.second}';

    }

    _writeCookie(m);

  }


  static bool deleteCookie(String name){

    var m = new Map();

    m[name]=' ';

    DateTime t = new DateTime.now().toUtc();

    m['expires'] = '${t.day}-${Month.getShort(t.month)}-${t.year} ${t.hour}:${t.minute}:${t.second}';

    _writeCookie(m);

  }


  static String getCookie(String name){

    Map c = _readCookie();

    return c.containsKey(name)? c['name'] : null;

  }

}

You can use it to delete cookie:

ClientCookie.deleteCookie('myCookie');

document.cookie returns String like this '<name>=<value>; <name>=<value>', document.cookie = '$name=$value' creates new cookie file with specified name and value (and optionally with other parameters like EXPIRES, PATH, etc.

Also noticed that value of expires should have strict pattern DD-MMM-YYYY HH:MM:SS and represents time in GMT.

Hope, this helps.

вторник, 28 февраля 2012 г., 15:17:33 UTC+6 пользователь Timur написал:
Hi all,
Reply all
Reply to author
Forward
0 new messages