DEV Community

Do Van Phuc
Do Van Phuc

Posted on

Cookie

Cookie là dữ liệu được lưu trữ trong một file (nằm trong máy tính).
Cookie được lưu trữ ở dạng name = value.
Mục đích tương tự khai báo biến, nhưng khác ở chỗ:
● Biến thông thường khi load lại trang sẽ mất.
● Biến lưu trong cookie sẽ tồn tại trong một khoảng thời gian do bạn tự thiết lập.

Các thao tác với cookie

Tạo cookie:

Cú pháp:
document.cookie = "name=value";
Hàm để thiết lập giá trị cookie:

function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Enter fullscreen mode Exit fullscreen mode

Lấy giá trị cookie:

Cú pháp:
var giatri = document.cookie;
Hàm để lấy một giá trị cookie:

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Enter fullscreen mode Exit fullscreen mode

Đổi giá trị cho cookie:

Cú pháp:
document.cookie = "name=value";

Xoá cookie:

Chỉ cần xét lại giá trị ngày hết hạn expires về những thời gian trước đây.
Cú pháp:
document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Hàm để xoá cookie:

function deleteCookie(cname) {
document.cookie = `${cname}=; expires=Thu, 01 Jan 1970 00:00:00 UTC`;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)