Empty localStorage data stored when the browser closes

Empty localStorage data stored when the browser closes

Explanation

Due to different pages or tabsCan not sharesessionStorage information, so the project will be logged stored in localStorage in.

demand

Required when the user closes the browser, the localStorage data stored in the clear.

Solutions and ideas

Initially thought onunload method, impatient direct line and up

window.onunload=()=>{
    localStorage.clear();
}

Tried quite so that, under flattered to change a bug ~~~ heart is big # 24,
not long before the fat with F5 to refresh the next page, look ignorant force! ! Skip to login page directly, because the onunload refresh on or off when we will call in the browser, so! When fat refresh the page, the user's login status to cleared away. (I pot my pot)
since onunload does not work, then it will be cookie and localStorage combined all at once.

  1. cookie will be automatically cleared when you exit the browser;
  2. We set localStorage and set a time cookie to monitor our localStorage ;
//设置cookie    
function setCookie(name, value, seconds) {
  seconds = seconds || 0;   //seconds有值就直接赋值,没有为0    
  var expires = "";
  if (seconds != 0) {      //设置cookie生存时间    
    var date = new Date();
    date.setTime(date.getTime() + (seconds * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expires + "; path=/";   //转码并赋值    
}
function setInof(key, value) {
  localStorage.setItem(key, value);
  setCookie(key,value)//存储localStorage的同时,也存储一个cookie来监听
}
  1. The next very comfortable, by determining whether a cookie to decide whether to remove our localStorage
  //取得cookie    
  function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';'); //把cookie分割成组    
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i]; //取得字符串    
      while (c.charAt(0) == ' ') { //判断一下字符串有没有前导空格    
        c = c.substring(1, c.length); //有的话,从第二位开始取    
      }
      if (c.indexOf(nameEQ) == 0) { //如果含有我们要的name    
        return unescape(c.substring(nameEQ.length, c.length)); //解码并截取我们要值    
      }
    }
    return false;
  }
 if(!getCookie('Token')){
   //清除
    localStorage.clear();
  }

OK! Satisfactorily resolved the problem! I hope to see this article can help you ( ). I was fat, not lean back 150 pounds of men do not change the name! ! ! About this there is nothing wrong with welcome messages criticism and correction, thanks! thank! thank!

Published an original article · won praise 1 · views 55

Guess you like

Origin blog.csdn.net/weixin_44272418/article/details/105282703