asp 退出登录修改cookie能进入后台_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();  }}

使用示例:

//定义keyconst 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或不传,表示关闭浏览器后就被清除,截图预览:

a112b3946f35c7bc9830731967b2816d.png

当登录的信息存储为这种形式,可以实现关闭浏览器,就清除登录信息。也可以再配合登录有效期,总不能“只要不关浏览器,就不退出登录了”。

文档:

MDN Cookie(https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)W3c Cookie(https://www.w3school.com.cn/js/js_cookies.asp)菜鸟教程 Cookie(https://www.runoob.com/js/js-cookies.html)

有补充请在评论区留言。

091ba7124a578a534ef576f9ecd7c257.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值