How to remove a cookie by using Javascript?

后端 未结 5 1264
后悔当初
后悔当初 2021-01-17 09:00

How to remove the cookie set by

javascript:void(document.cookie=”PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;p         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 09:59

    Agreed, @bobince. The official documentation says to use Date.toUTCString() for cookie expiration dates.

    I am 95% sure that you must set an expiration date when creating the cookie crumb if you want to force its removal later. A cookie crumb created without an explicit expiration date is a session cookie (crumb) by default, which means that it is not removed until the browser is closed. I recall trying to expire a session cookie to no avail, in the past.

    If you do set an expiration date on the cookie crumb in the first place, remember that you can use a variable for the new expiration date.

    // assuming a non-session cookie crumb called "someCrumbName" exists:
    var now = new Date();
    var expirationDate = new Date();
    var someValue = "foo";
    
    // set the expiration date to a week ago and delete the cookie
    expirationDate.setDate(now.getDate() - 7);
    document.cookie = "someCrumbName=" + someValue + ";expires=" + expirationDate.toUTCString();
    

提交回复
热议问题