Clear the contents of localStorage after closing the browser

It is not possible to clear the contents of localStorage after the browser is closed, because JavaScript cannot continue executing after the browser is closed. However, we can check whether there is a mark indicating that the browser was closed last time when the browser is opened next time, and if so, clear the contents of localStorage.


To achieve this, you can modify the event listener in the method to store a flag (for example subscriptions) in localStorage indicating that the browser is closed. Then, the next time you start the app, check that flag and clear localStorage if necessary. The following is the modified part: This is the dva writing method of react, and the idea is the samesetupwindow.unloadbrowserClosed

subscriptions

subscriptions: {  
  setup({ dispatch, history }) {  
    const data = localStorage.getItem('counterData');  
    const browserClosed = localStorage.getItem('browserClosed');  
      
    if (browserClosed) {  
      localStorage.clear();  
    } else if (data) {  
      dispatch({ type: 'saveData', payload: JSON.parse(data) });  
    }  
  
    // 监听 window.beforeunload 事件  
    window.addEventListener('beforeunload', () => {  
      dispatch({ type: 'saveData' });  
    });  
  
    // 监听 window.unload 事件  
    window.addEventListener('unload', () => {  
      localStorage.setItem('browserClosed', 'true');  
    });  
  },  
},  

In the code above, browserClosedthe flags are checked first. If it exists, clear all data in localStorage, otherwise, if there is counterDatadata, restore the data. unloadThe event listener browserClosedsets the flag to true. This way, after closing the browser, the contents of localStorage will be cleared the next time the application is opened.

Replenish:

sessionStorage is a client-side storage method, similar to localStorage. But sessionStorage's lifetime only lasts until the browser or tab is closed. Therefore, after closing the browser or tab, the contents of sessionStorage are automatically cleared without writing additional code.

Guess you like

Origin blog.csdn.net/weixin_46600931/article/details/130746369