How to clear local storage when a particular tab is closed and not when browser is closed in Angular 2?

13,308

Solution 1

You can use sessionStorage instead. Unlike localStorage, it will not persist the data across tabs. Here is some more information about it.

Session storage works the same as local storage but the only difference is that it will clear data when the current tab is closed. If you open a new tab for this application it will redirect to login.

You should read the following article which will help you to clearly understand the different storage options available in the browser. Sharing sessionStorage between tabs...

Solution 2

The below trick can workout to differentiate between Refresh and Tab/browser closure. Here i am comparing the timestamp of the request before unload with afterload. In the below example , If the timediff in seconds is less than 10sec , browser will consider it as Refresh and if the time diff is more than 10sec , it will be considered as tab closed.

You can redefine the difference based on the http Request timetaken at your client. If its more , just increase it to 50 secs. If its more than that , on load, browser will clear the local storage and reload the site.

<script>
    window.onbeforeunload = function(e) {
        let date = Date.now();
        localStorage.setItem("lastactivity", date);
    };
    window.onload = function() {
        let date1 = localStorage.getItem('lastactivity');
        let date2 = Date.now();
        if (date1 !== undefined) {
         let difference = date2 - date1;
         let diff = ((difference) / 1000).toFixed(0);
         if (diff > 10) {
            localStorage.clear();
            //localStorage.removeItem(key);  for removing a single item
            location.reload();
         }
        }
    };
</script>

**In Particular to angular 2 , add this piece of code in index.html before </body> tag.

Share:
13,308
Dutta
Author by

Dutta

Updated on June 25, 2022

Comments

  • Dutta
    Dutta almost 2 years

    My requirements are:

    1. I have to clear localstorage when the browser is closed.
    2. Already, i tried with onbeforeunload. It is executing on browser close event.
    3. Since there are multiple browser tabs opened, the localStorage is retaining the old values and not redirecting it to the Login page.

    Below is my sample code.

    Kindly suggest any solution for this.

    @HostListener('window:onbeforeunload', ['$event'])
    unloadHandler(event) {
        localStorage.clear();
    }
    

    Also, attached the code screenshot