如何在 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>
廣告