Reading cookie expiration date

前端 未结 7 1167
我在风中等你
我在风中等你 2020-11-28 11:50

Is it possible to read cookie expiration date using JavaScript?

If yes, how? If not, is there a source I can look at?

相关标签:
7条回答
  • 2020-11-28 12:23

    If you have control over the code where the cookie is set, then you can add code to store the expiration date in the browser's local storage for later retrival. For example:

    // set cookie with key and value to expire 30 days from now
    var expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
    document.cookie = [
        "key=value",
        "expires=" + expires.toUTCString()
    ].join("; ");
    
    // store cookie expiration date for key in local storage
    if (window.localStorage) {
        localStorage.setItem("keyExpires", expires.toISOString());
    }
    

    Later, you can lookup when the cookie expires in local storage. For example:

    var expires = localStorage.getItem("keyExpires");
    

    Local storage currently has broad support.

    https://caniuse.com/#feat=namevalue-storage

    0 讨论(0)
提交回复
热议问题