Cookie 過期處理是前端常見需求:用戶登出、會話超時、隱私合規清理。本文總結三種強制 Cookie 過期的方法,涵蓋 jQuery Cookie 插件、原生 JS、服務端協同方案。
需引入 `jquery.cookie.js`
// 1. 設置過期時間為過去 (例如 1 分鐘前)
var date = new Date();
date.setTime(date.getTime() - 60 * 1000); // 過去 1 分鐘
$.cookie('cookieName', '', {
expires: date,
path: '/', // 必須與設置時一致
domain: '.example.com', // 可選,需與設置時一致
secure: true // 可選,需與設置時一致
});
// 2. 插件內部會自動處理 expires 為 Date 對象的情況
// 等效於: document.cookie = "cookieName=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=.example.com; secure";
/**
* 刪除 Cookie 通用函數
* @param {string} name - Cookie 名稱
* @param {string} path - 路徑 (默認 '/')
* @param {string} domain - 域名 (可選,需與設置時一致)
*/
function deleteCookie(name, path = '/', domain = '') {
var expires = 'expires=Thu, 01 Jan 1970 00:00:00 GMT';
var pathStr = 'path=' + path;
var domainStr = domain ? 'domain=' + domain : '';
var secureStr = location.protocol === 'https:' ? 'secure' : '';
document.cookie = name + '=;' + expires + ';' + pathStr + ';' + domainStr + ';' + secureStr;
}
// 使用示例
deleteCookie('sessionId'); // 默認 path=/
deleteCookie('cart', '/shop'); // 指定路徑
deleteCookie('token', '/', '.example.com'); // 跨子域
// 原文有語法錯誤,此處修正
var expiresDate = new Date();
expiresDate.setTime(expiresDate.getTime() - 1000); // 過去 1 秒
$.cookie("__cookie__", 'helloworld', {
path: '/',
expires: expiresDate
});
function setCookie(name, value, options = {}) {
var str = name + '=' + encodeURIComponent(value);
if (options.expires) {
var date = options.expires;
if (typeof date === 'number') { // 天數
date = new Date();
date.setDate(date.getDate() + options.expires);
}
str += ';expires=' + date.toUTCString();
}
if (options.path) str += ';path=' + options.path;
if (options.domain) str += ';domain=' + options.domain;
if (options.secure) str += ';secure';
if (options.sameSite) str += ';samesite=' + options.sameSite;
document.cookie = str;
}
// 刪除 Cookie
function removeCookie(name, options = {}) {
setCookie(name, '', {
...options,
expires: -1 // 過去時間
});
}
// 使用
removeCookie('userId', { path: '/', domain: '.example.com' });
function clearAllCookies(path = '/', domain = '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var name = cookies[i].split('=')[0].trim();
deleteCookie(name, path, domain);
}
}
// 登出時調用
clearAllCookies('/', '.example.com');
<html>
<head>
<script src="jquery-3.6.0.min.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$(function() {
// 設置測試 Cookie
$('#setBtn').click(function() {
$.cookie('testCookie', 'value123', { expires: 7, path: '/' });
alert('已設置,7天過期');
});
// 方法一:jQuery Cookie 插件刪除
$('#delPlugin').click(function() {
$.cookie('testCookie', '', { expires: -1, path: '/' });
alert('插件法刪除完成');
});
// 方法二:原生 JS 刪除
$('#delNative').click(function() {
document.cookie = 'testCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
alert('原生法刪除完成');
});
// 方法三:工具函數刪除
$('#delUtil').click(function() {
removeCookie('testCookie', { path: '/' });
alert('工具函數刪除完成');
});
});
</script>
</head>
<body>
<button id="setBtn">設置 Cookie</button>
<button id="delPlugin">jQuery 插件刪除</button>
<button id="delNative">原生 JS 刪除</button>
<button id="delUtil">工具函數刪除</button>
</body>
</html>