Reputation: 33
Need to clear localstorage item when close browser (Chrome, Firefox, IE, Safari...).
I tried this following code, but it works only on the page refreshing time not at browser closing.
Type 1:
$(window).unload(function(){
localStorage.removeItem(key);
});
Type 2:
window.onbeforeunload = function (e) {
message = "Are you sure you want leave?";
e.returnValue = message;
return message;
};
But both are working on page refreshing action only.
Upvotes: 0
Views: 801
Reputation: 514
EDIT: You have said you need to clear local storage before the browser closes. This is what session storage is for. It behaves the same, but will be cleared at the end of the session. Use session storage.
There is no consistent way to run a function before the window closes across all browsers. This is partially a security measure as if, for example, a malicious website wanted to stop the browser window from closing, they would probably be able to exploit this behaviour to do so.
beforeunload
is the most compatible hook to use, but should not be relied on for critical logic. A browser window may close outside of the control of the browser, for example, if the computer shuts down. If you need to run a function to retain information, it is best to do so dynamically when that information changes, either with AJAX to store the data on the server, or using local storage.
Upvotes: 2