【问题标题】:Delete specific cookie with Javascript使用 Javascript 删除特定 cookie
【发布时间】:2019-06-27 00:28:36
【问题描述】:

我需要从网站中删除特定的 cookie。起初我尝试了几种删除所有 cookie 的方法,但没有一个能正常工作(并非所有 cookie 都被删除)。

我也尝试了下面的代码来找到我需要删除的cookie,但是找到后我不知道如何删除它。

谁能帮忙?

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();

【问题讨论】:

    标签: javascript cookies session-cookies


    【解决方案1】:

    看看这个。

    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');
    } 
    

    为了删除 cookie,请将过期日期设置为过去。它会自动删除

    【讨论】:

    • 我试过这个,但它似乎只有在“过期/最大年龄”列值为“会话”时才有效。当该列的值包含特定日期时,它不会删除它。日期示例为“2021-06-15T16:29:48.107Z”
    • 这应该不是问题。我可以使用该功能删除任何 cookie。我已经用我的电脑测试过了。有用。深入了解代码。
    • 我相信你已经测试过了,但是在我的网站上它不起作用,我不知道为什么。
    • 别担心。尝试使用 mozilla 的 api,他们有一个很好的工具来处理你的任务。 developer.mozilla.org/en-US/docs/Web/API/Document/cookie/…
    • 您是否尝试过手动删除然后尝试创建和使用上述功能。
    猜你喜欢
    • 2013-07-20
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多