How to delete a cookie?

后端 未结 8 1560
说谎
说谎 2020-11-22 02:08

Is my function of creating a cookie correct? How do I delete the cookie at the beginning of my program? is there a simple coding?

function createCookie(name,         


        
8条回答
  •  星月不相逢
    2020-11-22 02:15

    To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

    1.

        function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
            var expireDate = new Date();
            if (expireDays) {
                expireDate.setDate(expireDate.getDate() + expireDays);
            }
            if (expireHours) {
                expireDate.setHours(expireDate.getHours() + expireHours);
            }
            if (expireMinutes) {
                expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
            }
            if (expireSeconds) {
                expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
            }
            document.cookie = key +"="+ escape(value) +
                ";domain="+ window.location.hostname +
                ";path=/"+
                ";expires="+expireDate.toUTCString();
        }
    
        function deleteCookie(name) {
            setCookie(name, "", null , null , null, 1);
        }
    

    Usage:

    setCookie("reminder", "buyCoffee", null, null, 20);
    deleteCookie("reminder");
    

    2

        function setCookie(params) {
            var name            = params.name,
                value           = params.value,
                expireDays      = params.days,
                expireHours     = params.hours,
                expireMinutes   = params.minutes,
                expireSeconds   = params.seconds;
    
            var expireDate = new Date();
            if (expireDays) {
                expireDate.setDate(expireDate.getDate() + expireDays);
            }
            if (expireHours) {
                expireDate.setHours(expireDate.getHours() + expireHours);
            }
            if (expireMinutes) {
                expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
            }
            if (expireSeconds) {
                expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
            }
    
            document.cookie = name +"="+ escape(value) +
                ";domain="+ window.location.hostname +
                ";path=/"+
                ";expires="+expireDate.toUTCString();
        }
    
        function deleteCookie(name) {
            setCookie({name: name, value: "", seconds: 1});
        }
    

    Usage:

    setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
    deleteCookie("reminder");
    

提交回复
热议问题