Javascript implements workarounds for obtaining cookie expiration times

  • 2020-03-30 03:43:41
  • OfStack

Javascript and dynamic pages cannot get the expiration time of cookies, which is managed by the browser. Javascript and dynamic pages can only set the expiration time, which cannot be obtained through the document.cookie (javascript) or cookie.expires (asp.net) properties.


<%@page language="C#" Debug="true"%>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie hc = Request.Cookies["abc"];
        if (hc != null)
        {
            Response.Write(hc.Expires);//0001-1-1 0:00:00
            Response.End();
           
        }
    }
</script>

Although the cookie in asp.net has an Expires property, the Response. Write output Expires property gets 0001-1-1 0:00:00 (DateTime. MinValue).
 
Be sure to get the expiration time. You need another cookie value to record the expiration time of the corresponding cookie. As follows:


<script>
    var d = new Date();
    d.setHours(d.getHours() + 1); //1 hour overdue
    document.cookie = 'testvalue=123;expires=' + d.toGMTString(); //Store the cookie value
    document.cookie = 'testexp=' + escape(d.toLocaleString()) + ';expires=' + d.toGMTString(); //Store the cookie expiration time, to get the expiration time of the cookie testvalue, by obtaining the testexp cookie to achieve
   
</script>


Related articles: