Reading cookie expiration date

2019-01-09 08:32发布

Is it possible to read cookie expiration date using JavaScript?

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

6条回答
Fickle 薄情
2楼-- · 2019-01-09 08:35

There are some who will find this contentious - but one solution is to create another cookie at the same time and store the time/stamp in it parallel with whichever original cookie is created. Update them both at the same time and that way you can easily get the time from your new cookie (Alternatively append the time/stamp in your source cookie).

The reason this would be contentious is that over the years the idea of storing cookies on a users PC isn't popular because you are taking up their space. However I really doubt a small timestamp cookie would be too horrific.

Its worth remembering that if a time has passed then the browser will not report that cookie available. The browser may show the cookie present but when JS tries to access it - it won't be able too.

Additionally I found that WebDeveloper toolbar in Firefox shows cookies that have passed but under Firefox > Privacy settings they are updated correctly.

查看更多
ら.Afraid
3楼-- · 2019-01-09 08:50

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

查看更多
叛逆
4楼-- · 2019-01-09 08:51

If you are using Chrome you can goto the "Application" tab (within Developer Tools) and find the item "Cookies" in the left sidebar. From there select the domain you are checking the set cookie for and it will give you a list of cookies associated with that domain, along with their expiration date.

查看更多
爷的心禁止访问
5楼-- · 2019-01-09 08:51

Another way to do this would be to write the expiration date into the body of the cookie and then reread it from there for subsequent rewrites. I've gotten this to work with the fantastic js-cookies library.

Setting looks like this:

// Set cookie expiration as a number (of days)
var paywallDuration = 30;

// When you set the cookie, add the `expires` key/value pair for browsers
// Also add `expirationDate` key/value pair into JSON object
Cookies.set('article-tracker', {
  expirationDate : paywallDuration,
  totalArticlesRead: 1
}, {
  expires : paywallDuration,
  domain : 'example.com'
});

Reading your cookie and rewriting is straight-forward with this method. Use js-cookie's getJSON() method to read the expiration date you set. Then, use that date twice when you rewrite your cookie - again in the JSON object and then for the browser with expires:

var existingPaywallDuration = Cookies.getJSON('article-tracker').expirationDate;

Cookies.set('article-tracker', {
  expirationDate: existingPaywallDuration,
  totalArticlesRead: 4
}, {
  expires : existingPaywallDuration,
  domain : 'example.com'
});
查看更多
别忘想泡老子
6楼-- · 2019-01-09 08:57

There is a work-around to OP's question. I do it like this:

    **Set the cookie:**
    function setCookie(cnavn, cvaerdi, udloeb) {
      var d = new Date();

      d.setTime(d.getTime() + udloeb*24*60*60*1000 + 2*60*60*1000);
      var expires = "expires=" + d.toUTCString() + ";";
      document.cookie = cnavn + "=" + cvaerdi + "_" + d.toUTCString() + "_/;expires=" + d.toUTCString() + "path=/;";
    }

    **Display the cookies:**
    function showCookies() {
      if(document.cookie.length != 0) {
        var cookiesArray = document.cookie.split("; "),
            cString = '',
            wrapper = document.getElementById("allCookies");

        for(var i=0; i<cookiesArray.length; i++) {
            var cookieNameArray = cookiesArray[i].split("="),
                cookieValueArray = cookieNameArray[1].split("_");

            cString += "<p><b>" + (i+1) + "</b><br />Cookie name: " + cookieNameArray[0] + "<br />Cookie value: " + cookieValueArray[0] + "<br />Expires: " + cookieValueArray[1] + "<br />Path: " + cookieValueArray[2] + "</p>";
        }
        wrapper.innerHTML = cString;
      }
    }

    **HTML:**
    <p onclick="showCookies()">Show me the cookies!</p>
    <div id="allCookies"></div>
查看更多
何必那么认真
7楼-- · 2019-01-09 09:00

It is not possible to get the expiration date of a cookie through Javascript; only key-value pairs are exposed through document.cookie.

查看更多
登录 后发表回答