進(jìn)入我的主頁夷蚊,查看更多JS的分享构挤!
我的代碼有多短,本篇內(nèi)容就有多短惕鼓!
本地存儲(chǔ)對(duì)比:
- sessionStorage筋现,關(guān)閉窗口就被清除;
- localStorage箱歧,一直存在直到手動(dòng)刪除矾飞;
- cookie,設(shè)置有效期呀邢,可以直接實(shí)現(xiàn)標(biāo)題的需求
今天不想多說話洒沦,直接貼上代碼:
//判斷是否支持 比如瀏覽器開啟了隱私模式
var isCookie = () = >{
return navigator.cookieEnabled;
};
//存儲(chǔ)
function setCookie(cname, cvalue, exdays = 0) {
cvalue = encodeURIComponent(JSON.stringify(cvalue));
if (exdays > 0) {
var d = new Date().getTime() + exdays * 24 * 3600 * 1000 + 8 * 3600 * 1000;
var expires = "expires=" + new Date(d).toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
} else {
document.cookie = cname + "=" + cvalue + ";" + ";path=/";
}
}
//獲取
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) {
let d = c.substring(name.length, c.length);
return JSON.parse(decodeURIComponent(d));
}
}
return "";
}
//獲取 通過正則
// function getCookie(name) {
// var arr,
// reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
// if ((arr = document.cookie.match(reg))) {
// return JSON.parse(decodeURIComponent(arr[2]));
// } else {
// return null;
// }
// }
//刪除
function deleteCookie(name) {
var date = new Date();
date.setTime(date.getTime() - 1);
var delValue = getCookie(name);
if (delValue) {
document.cookie = name + "=" + delValue + ";expires=" + date.toGMTString();
}
}
使用示例:
//定義key
const tk = "tk2020";
const uk = "uk2020";
//保存
setCookie(tk, "14332239527007001", 0);
setCookie(uk, { id: 1, name: "以氣御碼" }, 0);
//獲取
let token = getCookie(tk);
let user = getCookie(uk);
console.log(token);
console.log(user);
當(dāng)使用setCookie時(shí),傳0或不傳价淌,表示關(guān)閉瀏覽器后就被清除申眼,截圖預(yù)覽:
當(dāng)?shù)卿浀男畔⒋鎯?chǔ)為這種形式瞒津,可以實(shí)現(xiàn)關(guān)閉瀏覽器,就清除登錄信息括尸。也可以再配合登錄有效期巷蚪,總不能“只要不關(guān)瀏覽器,就不退出登錄了”濒翻。
文檔:
有補(bǔ)充請(qǐng)?jiān)谠u(píng)論區(qū)留言屁柏。