1

The question was: "How to clean localeStorage only after closing the browser (not closing the browser tab and reloading the page). And this must be implemented in the Vue component. Found the following solution (Clear localStorage on tab/browser close but not on refresh):

window.onbeforeunload = function (e) {
    window.onunload = function () {
            window.localStorage.isMySessionActive = "false";
    }
    return undefined;
};

window.onload = function () {
            window.localStorage.isMySessionActive = "true";
};

But I do not understand how to properly and where to call these listeners.

KolisbikBoh
  • 85
  • 2
  • 10

1 Answers1

2

You can simply register your listeners in your main.js file or in your App.vue file

main.js

import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;

new Vue({
  beforeMount() {
    window.addEventListener("load", this.onLoad);
    window.addEventListener("beforeunload", this.onUnload);
  },
  beforeDestroy() {
    window.removeEventListener("load", this.onLoad);
    window.removeEventListener("beforeunload", this.onUnload);
  },
  methods: {
    onLoad(event) {
      window.localStorage.setItem("isMySessionActive", true);
    },
    onUnload(event) {
      window.localStorage.setItem("isMySessionActive", false);
    }
  },
  render: (h) => h(App)
}).$mount("#app");

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" width="25%">
    <HelloWorld msg="Hello World!"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  beforeMount() {
    window.addEventListener("load", this.onLoad);
    window.addEventListener("beforeunload", this.onUnload);
  },
  beforeDestroy() {
    window.removeEventListener("load", this.onLoad);
    window.removeEventListener("beforeunload", this.onUnload);
  },
  methods: {
    onLoad(event) {
      window.localStorage.setItem("isMySessionActive", true);
    },
    onUnload(event) {
      window.localStorage.setItem("isMySessionActive", false);
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
ptheodosiou
  • 390
  • 3
  • 17