Kéo dài vòng đời cookie quá phiên trình duyệt hiện tại bằng cách đặt ngày hết hạn và lưu ngày hết hạn trong cookie. Làm bằng cách đặt thuộc tính expires thành ngày/giờ cụ thể.
Ví dụ: Hết hạn sau 1 giờ
<html>
<head>
<script>
function WriteCookie() {
var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000); // +1 giờ (ms)
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>
Lưu ý: escape() đã deprecated. Nên dùng encodeURIComponent(). Cài cookie đúng cách: document.cookie = "name=value; expires=...; path=/".