简体   繁体   中英

Delete specific cookie with Javascript

I need to delete a specific cookie from a website. At first I have tried several ways to delete ALL cookies, however none of them worked properly (not all cookies were deleted).

I also tried the below code to find the cookie I need to delete, but I can't figure out how to delete it after found it.

Can anyone help?

function getCookie(name) {
            var dc = document.cookie;
            var prefix = name + "=";
            var begin = dc.indexOf("; " + prefix);
            if (begin == -1) {
                begin = dc.indexOf(prefix);
                if (begin != 0) return null;
            }
            else
            {
                begin += 2;
                var end = document.cookie.indexOf(";", begin);
                if (end == -1) {
                end = dc.length;
                }
            }

            return decodeURI(dc.substring(begin + prefix.length, end));
        } 

        function deleteCookie() {
            var myCookie = getCookie("dropin_date");

            if (myCookie == null) {

            }
            else {
                // if cookie exists delete it
            }
        }

        deleteCookie();

check this out.

function accessCookie(cookieName) {
    var name = cookieName + "=";
    var allCookieArray = document.cookie.split(';');
    for(var i=0; i<allCookieArray.length; i++)
    {
      var temp = allCookieArray[i].trim();
      if (temp.indexOf(name)==0)
      return temp.substring(name.length,temp.length);
      }
    return "";

}

var delete_cookie = function(name) {
   document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};    

var mycookie = accesCookie('test');

if(mycookie != ''){
   delete_cookie('test');
} 

In order to delete a cookie set the expires date in the past. it will delete automatically

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