如何在 JavaScript 中設定在 30 分鐘到期的 cookie?


可以透過設定過期日期並將過期日期儲存在 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>

更新時間: 09-01-2020

6K+ 瀏覽量

開啟您的 職業

透過完成課程獲取認證

開始
廣告
© . All rights reserved.