如何在 JavaScript 中設定 Cookie 在 30 分鐘後過期?


透過設定過期時間並在 cookie 中儲存過期時間,你可以延長 cookie 超出當前瀏覽器會話的生命週期。這可以透過將“expires”屬性設定為某個日期和時間來實現。

示例

你可以嘗試執行以下示例以設定 cookie 在 30 分鐘後過期

實際示例

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

更新於: 2020 年 1 月 9 日

6K+ 瀏覽量

開啟你的職業生涯

透過完成教程取得認證

開始
廣告
© . All rights reserved.