cookiesdart

How to delete a cookie in Dart


How do I delete a cookie in dart when running on the client?

I have tried to delete it by setting it to an empty string using

document.cookie = 'cookie_to_be_deleted=""';

If I print the value of cookie after this line I get a semicolon-separated list of key value pairs with two instances of "cookie_to_be_deleted". One has the original value I was hoping to delete and the other has an empty string for its value.


Solution

  • Try this:

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

    Found these utilities at 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);
    }