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

ski*_*kip 10 javascript jquery

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

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

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

谢谢.

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
    }

});
Run Code Online (Sandbox Code Playgroud)

Rok*_*jan 11

if( $.cookie('yourCookie') === null ) {
    // EXPIRED
} else {
    // DO SOMETHING ELSE
}
Run Code Online (Sandbox Code Playgroud)

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

$.cookie('yourCookie') === null ? /* EXPIRED */ : /* DO SOMETHING ELSE */;
Run Code Online (Sandbox Code Playgroud)

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


小智 5

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

  • 浏览器还没有这样做,这就是问题所在。我正在使用其Mozilla Firefox,但尚未更改任何设置。 (2认同)