0

I want to clear my local storage after closing the browser, for that I control all active tabs using sessionStorage

so, my App.js looks like this:

    window.onload = () => {
        var tabID = sessionStorage.getItem("tab_id");
        if (tabID === null) {
            var hash = Math.random(10**5).toString(36)
            sessionStorage.setItem("tab_id", hash);
            var allTabs = localStorage.getItem("all_tabs");
            if (allTabs ==null || allTabs==''){
                console.log(1)
                allTabs=[]
            }
            else{
                console.log(1, allTabs)
                allTabs = allTabs.split(',');
            }
            console.log(allTabs)
            allTabs.push(hash)
            console.log(hash, 'local', allTabs)
            localStorage.setItem("all_tabs", allTabs);
        }
    }

    window.onunload  = () => {
        var tabID = sessionStorage.getItem("tab_id");
        var allTabs = localStorage.getItem("all_tabs");
        var locItemsArr = allTabs.split(',');

        var ind = locItemsArr.indexOf(tabID)
        locItemsArr.splice(ind,1)
        localStorage.setItem("all_tabs", locItemsArr.toString());

        if (localStorage.getItem("all_tabs") == "" ) {
            console.log('clear')
            localStorage.clear()
        }
    }

However, I didn't took into account the fact that onunload will also be triggered when the page is updated. Is there any way to understand if the page is closing or just being updated to clear localStorage only after closing?

Egoinc
  • 1
  • 1
    You could include a "log out" type button for users to click to signify that they are done with your app and therefore you'd know that it's safe to clear out the storage. – Scott Marcus May 25 '23 at 21:12
  • Use sessionStorage, which is cleared when a page is closed by not cleared when reloaded. See this answer: https://stackoverflow.com/questions/568977/identifying-between-refresh-and-close-browser-actions#:~:text=When%20we%20refresh%20the%20page,It%20will%20trigger%20ONUNLOAD%20event. – ionosphere May 25 '23 at 21:32
  • @ionosphere I already use session storage to save tab id, but i need to but I need to keep track of the number of open/closed tabs with my react app , so I collect these ids in localStorage I don't quite understand where exactly you suggest using sessionStorage for me? – Egoinc May 25 '23 at 21:41
  • @ScottMarcus I can't use logout button, my goal is to clear localStorage after closing browser. I already have logout button, but however, I lot of user didn't clock "log out" before leave the page. – Egoinc May 25 '23 at 21:43
  • @Egoinc: You should be able to check whether the tab id saved to session storage is null right after you get it with `getItem` and if so, the event is a page close event rather than a reload event. – ionosphere May 25 '23 at 21:52
  • As a user, I'd say that the best thing to do is to have the same behavior with reloading and getting out and on a page again. Imagine there's a bug in your website and it gets solved by clearing out the local storage. The user would expect that hitting the refresh button and closing and re-opening the tab have the same behavior. So my advice is to not ignore the user expectations on how browsers work – Christian Vincenzo Traina May 25 '23 at 22:08

1 Answers1

0

I try to do sth like this, but it didn't work stable, however after some improvements it could be a possible solution

var p
function print_nav_timing_data() {
    // Use getEntriesByType() to just get the "navigation" events
    var perfEntries = performance.getEntriesByType("navigation");

    for (var i = 0; i < perfEntries.length; i++) {
        console.log("= Navigation entry[" + i + "]");
        p = perfEntries[i];
        console.log("type = " + p.type);
    }
}

window.onload = () => {
    var tabID = sessionStorage.getItem("tab_id");
    if (tabID === null) {
        var hash = Math.random(10**5).toString(36)
        sessionStorage.setItem("tab_id", hash);
        var allTabs = localStorage.getItem("all_tabs");
        if (allTabs ==null || allTabs==''){
            console.log(1)
            allTabs=[]
        }
        else{
            console.log(1, allTabs)
            allTabs = allTabs.split(',');
        }
        console.log(allTabs)
        allTabs.push(hash)
        console.log(hash, 'local', allTabs)
        localStorage.setItem("all_tabs", allTabs);
    }
}

window.onbeforeunload  = () => {
    print_nav_timing_data()
    console.log("TYPE", p.type, typeof p.type)
    if (p.type != 'reload') {
    var tabID = sessionStorage.getItem("tab_id");
    var allTabs = localStorage.getItem("all_tabs");
    var locItemsArr = allTabs.split(',');

    var ind = locItemsArr.indexOf(tabID)
    locItemsArr.splice(ind,1)
    localStorage.setItem("all_tabs", locItemsArr.toString());

    if (localStorage.getItem("all_tabs") == "" ) {
        console.log('clear')
        localStorage.clear()
    }
  }
 }
Egoinc
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 26 '23 at 05:43