Javascript 如何测试javascript cookie是否已过期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9072385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:34:38  来源:igfitidea点击:

how to test if a javascript cookie has expired?

javascriptjquery

提问by skip

Is it possible to test if a javascript cookie has expired using?

是否可以测试 javascript cookie 是否已过期?

I need to do a few thing conditionally and two of those conditions are overlapping for which if it could be tested whether a cookie has expired then it will be easier for me to get things done.

我需要有条件地做一些事情,其中​​两个条件是重叠的,如果可以测试 cookie 是否已过期,那么我将更容易完成工作。

I am using jquery-1.5.jsand jquery.cookies.jsplugin.

我正在使用jquery-1.5.jsjquery.cookies.js插件。

Thanks.

谢谢。

CODE

代码

var jq = jQuery.noConflict();
jq(document).ready(function () {

    var timeStart, timeSubmit, timeLeft;
    timeSubmit = 5 * 60 * 1000;
    timeStart = jaaulde.utils.cookies.get("_watchman");
    try {
        if(jaaulde.utils.cookies.test()) {
            throw "err1";
        }
        else if(hasCookieExpired) {
            throw "err2";
        }
        else if(!timeStart) {
            jaaulde.utils.cookies.set("_watchman", String(new Date().getTime()), {path: '/path', expiresAt: new Date((new Date().getTime() + timeSubmit))});
            timeLeft = timeSubmit - (new Date().getTime() - Number(jaaulde.utils.cookies.get("_watchman")));
            timeCheck();
        }
        else {
            timeLeft = timeSubmit - (new Date().getTime() - Number(jaaulde.utils.cookies.get("_tts")));         

            timeCheck();
        }

    } catch(err) {
        //handle errors
    }

    function timeCheck() {
            if(timeLeft <= 0) {
                triggerSubmit();
            }
            else {
                setTimeout(triggerSubmit, timeLeft);    
                setInterval(showTimeLeft, 1000);
            }       
    }

    function triggerSubmit() {
        //submit it
    }

    function showTimeLeft() {
        //do something
    }

});

回答by Roko C. Buljan

if( $.cookie('yourCookie') === null ) {
    // EXPIRED
} else {
    // DO SOMETHING ELSE
}

Or like this using Ternary operator:

或者像这样使用三元运算符

$.cookie('yourCookie') === null ? /* EXPIRED */ : /* DO SOMETHING ELSE */;


https://github.com/carhartl/jquery-cookie(No longer maintained, archived)
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
https://github.com/js-cookie/js-cookie

https://github.com/carhartl/jquery-cookie(不再维护,存档)
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
https://github.com /js-cookie/js-cookie

回答by Caleb Joseph

A browser will automatically remove any cookie once it expires, so all you need to do is check whether the cookie exists or not.

浏览器会在任何 cookie 过期后自动删除它,因此您需要做的就是检查 cookie 是否存在。

回答by dmr

If you say that the browser did not remove the cookie, it's probably because your time zone is different from UTC.

如果您说浏览器没有删除cookie,那可能是因为您的时区与UTC 不同。

回答by FennRussel

To test, please enter below HTML code

要测试,请输入以下 HTML 代码

<label for="expsecs">Cookie expiration in seconds:</label>
<input type="text" id="expsecs" value="5" /><br />
<button id="setcookie">set cookie</button>
<button id="getcookie">get cookie</button>
<div id="cookiestatus">status</div>

Please enter below jQuery code

请输入下面的jQuery代码

function set_cookie() {
    var secs = parseInt($('#expsecs').val(), 10);
    if (isNaN(secs)) {
        secs = 5;
    }
    var now = new Date();
    var exp = new Date(now.getTime() + secs*1000);
    var status = '';
    document.cookie = 'ExpirationCookieTest=1; expires='+exp.toUTCString();
    if (document.cookie && document.cookie.indexOf('ExpirationCookieTest=1') != -1) {
        status = 'Cookie successfully set. Expiration in '+secs+' seconds';
    } else {
        status = 'Cookie NOT set. Please make sure your browser is accepting cookies';
    }

    $('#cookiestatus').text(status);
}

function get_cookie() {
    var status = '';
    if (document.cookie && document.cookie.indexOf('ExpirationCookieTest=1') != -1) {
        status = 'Cookie is present';
    } else {
        status = 'Cookie is NOT present. It may be expired, or never set';
    }
    $('#cookiestatus').text(status);
}

function init() {
    $('#setcookie').bind('click', set_cookie);
    $('#getcookie').bind('click', get_cookie);
}

$(init);

Check this in jsfiddle

jsfiddle 中检查这个