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

Cách đặt ngày hết hạn (expiry date) cho cookie trong JavaScript

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

Ví dụ: Hết hạn sau 1 tháng

<html>
  <head>
    <script>
      function WriteCookie() {
        var now = new Date();
        now.setMonth(now.getMonth() + 1); // +1 tháng
        cookievalue = escape(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>

Best practice: Luôn thêm path=/ để cookie áp dụng toàn site. Dùng encodeURIComponent() thay escape().