如何在 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.