Reading cookie expiration date

前端 未结 7 1174
我在风中等你
我在风中等你 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:21

    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'
    });
    

提交回复
热议问题