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 samesetup
window.unload
browserClosed
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, browserClosed
the flags are checked first. If it exists, clear all data in localStorage, otherwise, if there is counterData
data, restore the data. unload
The event listener browserClosed
sets 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.