js清浏览器历史缓存(只要关闭浏览器)
进入我的主页,查看更多JS的分享!
我的代码有多短,本篇内容就有多短!
本地存储对比:
- sessionStorage,关闭窗口就被清除;
- localStorage,一直存在直到手动删除;
- cookie,设置有效期,可以直接实现标题的需求
今天不想多说话,直接贴上代码:
//判断是否支持 比如浏览器开启了隐私模式
var isCookie = () = >{
return navigator.cookieEnabled;
};
//存储
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);
当使用setCookie时,传0或不传,表示关闭浏览器后就被清除,截图预览:
当登录的信息存储为这种形式,可以实现关闭浏览器,就清除登录信息。也可以再配合登录有效期,总不能“只要不关浏览器,就不退出登录了”。
文档:
有补充请在评论区留言。
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com