Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để đặt cookie hết hạn sau 1 giờ trong JavaScript?


Bạn có thể kéo dài tuổi thọ của cookie ngoài phiên trình duyệt hiện tại bằng cách đặt ngày hết hạn và lưu ngày hết hạn trong cookie. Điều này có thể được thực hiện bằng cách đặt thuộc tính "expires" thành một ngày và giờ.

Ví dụ

Bạn có thể thử chạy ví dụ sau để đặt cookie hết hạn sau 1 giờ -

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setTime(now.getTime() + 1 * 3600 * 1000);
               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>