如何在 JavaScript 中設定 Cookie 過期時間?


透過設定到期時間和將到期時間儲存到 Cookie 中,將 Cookie 的使用壽命延長到當前瀏覽器會話之外。這可以透過將“expires”屬性設定為日期和時間來實現。

示例

您可以嘗試執行以下示例,將 Cookie 的到期時間設定為 1 個月:

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() + 1 );
               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>

更新於: 2020 年 6 月 16 日

5,000+ 次瀏覽

開啟您的事業

完成課程獲得認證

入門
廣告