Cookie hết hạn sẽ tự động bị trình duyệt xóa, không đọc được qua document.cookie. Kiểm tra sự tồn tại:
Với jQuery Cookie Plugin
// Cách 1: if/else
if ($.cookie('myCookie') !== null) {
// Cookie tồn tại (chưa hết hạn)
} else {
// Cookie không tồn tại (hết hạn hoặc chưa set)
}
// Cách 2: Toán tử ternary
var checkCookie = $.cookie('myCookie') === null ? "Hết hạn/Chưa có" : "Còn hiệu lực";
Vanilla JS (không cần plugin)
function getCookie(name) {
var v = "; " + document.cookie;
var parts = v.split("; " + name + "=");
return parts.length === 2 ? parts.pop().split(";").shift() : null;
}
if (getCookie('myCookie') !== null) {
// Cookie tồn tại
}
Lưu ý: Không thể đọc được expires attribute từ client-side JS. Chỉ biết cookie còn tồn tại hay không.