How to clear localStorage data when closing the browser window

1. For single-page applications, such as vue, etc.

Put the window.onbeforeunloadlistening method in App.vue

<template>
  <div id="main" class="app-main">
    <router-view></router-view>
  </div>
</template>
 
<script>
  export default {
    
    
    data () {
    
    
      return {
    
    
        theme: this.$store.state.app.themeColor
      };
    },
    methods: {
    
    
 
    },
    mounted(){
    
    
      // 关闭浏览器窗口的时候清空浏览器缓存在localStorage的数据
      window.onbeforeunload = function (e) {
    
    
        var storage = window.localStorage;
        storage.clear()
      }
    }
 
  };
</script>
 

Second, for multi-page applications

1. The first solution (for vue)

In the same way on each page, just register this event in the mounted method.

2. The second solution (for native js)

Use cookies as sentinels, because cookies will disappear automatically when you close the browser by default, we judge whether there is a cookie when the web page is opened, if not, we clear the localStorage cache, and then set a cookie, so that you do not close the browser , the cookie will always exist, that is, your localStorage data will always exist.

one example

//设置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来监听
}
 //取得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();
  }

Guess you like

Origin blog.csdn.net/qq_41880073/article/details/123002788