如何在 JavaScript 中设置 Cookie 在 1 小时后过期?


你可以通过设置过期日期并在 Cookie 中保存过期日期来延长 Cookie 在当前浏览器会话之外的使用寿命。这可以通过将“expires”属性设置为日期和时间来实现。

示例

你可以尝试运行以下示例,将 Cookie 设置为在 1 小时后过期 -

<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>

更新日期: 16-6-2020

9 千次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.