Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

javascript - Clear localStorage on tab/browser close but not on refresh

Is there a way to detect tab close event to clear the localStorage. I need localStorage to share data across tabs. window.onbeforeunload event works fine but it has 2 issues for me:

  1. It also fires on page refresh which I dont want.
  2. I don't need confirm box on tab close.

Like when window is closed the sessionStorage is cleared. At same time I can clear localStorage but don't know what event to bind to. I checked a few questions already available but none seems to address this issue there are workarounds by using flags for click on links and form submits but not a clean way to do it. Kindly suggest any solution for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know that that is an old question, but I was just looking for a solution for this, but I couldn't find anything that works properly. Then I came up with a solution which is working fine for me.

What I did was to change the perspective, instead of clearing the local storage when the browser is closed I decided to clear it when it is opened. Users won't see the difference.

I just set a function that check the sessionStorage when the page is loaded, if it is empty the function gets the localStorage cleared; After that it sets a register to sessionStorage to ensure that the localStorage won't be emptied again just for having the page reloaded.

function clearStorage() {

    let session = sessionStorage.getItem('register');

    if (session == null) {
    
        localStorage.removeItem('remove');

    }
    sessionStorage.setItem('register', 1);
}
window.addEventListener('load', clearStorage);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...