简体   繁体   中英

Javascript cookie delete

If I create a cookie in Javascript document.cookie = 'unseen' how do I delete it when I navigate away from this page? This is the only cookie I am creating on the page.

Run this:

document.cookie = 'unseen=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

You're not deleting it, but telling the browser it's expired so it'll delete it.

Set it it to expire to a time in the past. Function from http://techpatterns.com/downloads/javascript_cookies.php

function Delete_Cookie( name, path, domain ) {
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
      ( ( path ) ? ";path=" + path : "") +
      ( ( domain ) ? ";domain=" + domain : "" ) +
      ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

Sometimes

document.cookie = 'unseen=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

but sometimes need to specify path, if the first one failed (not the case of your exact code)

document.cookie = 'unseen=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';

(or use the same library function for creating cookie, but set negative number instead of positive expiry time)

delete document.cookie

anyways i'm not sure if this is the right way to deal with cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM