Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách đặt cookie hết hạn sau 30 phút trong JavaScript

Kéo dài vòng đời cookie bằng cách đặt ngày hết hạn. Set thuộc tính expires thành ngày/giờ cụ thể.

Ví dụ: Hết hạn sau 30 phút

<html>
  <head>
    <script>
      function WriteCookie() {
        var now = new Date();
        var minutes = 30;
        now.setTime(now.getTime() + (minutes * 60 * 1000)); // ms
        cookievalue = encodeURIComponent(document.myform.customer.value) + ";";
        document.cookie = "name=" + cookievalue;
        document.cookie = "expires=" + now.toUTCString() + ";";
        document.write("Setting Cookies: " + "name=" + cookievalue);
      }
    </script>
  </head>
  <body>
    <form name="myform" action="">
      Enter name: <input type="text" name="customer"/>
      <input type="button" value="Set Cookie" onclick="WriteCookie()"/>
    </form>
  </body>
</html>

Công thức: minutes * 60 * 1000 chuyển phút sang milliseconds.