Is it possible to delete localStorage data/logout after closing tab/browser window but not for refreshing that page of the project. So cause if some closes it, user have to login again. Thanks
Asked
Active
Viewed 318 times
-1
-
7Try [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) instead. – 31piy Jun 08 '18 at 11:43
-
1Or look into https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload – Jun 08 '18 at 11:43
-
"window.onbeforeunload" working but also in refresh the page. page may be refresh again again but should not be remove my storage Data for the refresh page. function should only call while close the tab/windows. – Bishnu Kumar Bhakat Jun 08 '18 at 11:47
2 Answers
0
This should work:
localStorage.setItem("someVar","someValue");
window.onbeforeunload = function(){
localStorage.removeItem("someVar");
};
But it's better sessionStorage
sessionStorage.setItem("someVar","someValue");
When user leaves the page all items are removed

Emeeus
- 5,072
- 2
- 25
- 37
-
yes ! I did this but this is happening for also refreshing that page. – Bishnu Kumar Bhakat Jun 08 '18 at 11:54
-
So, you should .setItem when document load and remove it when onbeforeunload, because there is no tab close event https://stackoverflow.com/questions/3888902/detect-browser-or-tab-closing – Emeeus Jun 08 '18 at 12:18
0
If you want to delete anything on close of tab use sessionStorage
rather than localStorage
as:
sessionStorage.setItem("key","value");

Anshuman Jaiswal
- 5,352
- 1
- 29
- 46
-
hey sorry, it should be `sessionStorage` I typed incorrectly. Updated the answer. – Anshuman Jaiswal Jun 08 '18 at 12:05
-
`sessionStorage` does the same, where and how you are trying? Please add your code as well. – Anshuman Jaiswal Jun 08 '18 at 12:11
-
// window.onbeforeunload = function(){ // sessionStorage.removeItem("key"); // return ''; // }; at my app.run section – Bishnu Kumar Bhakat Jun 08 '18 at 12:17
-
@BishnuKumarBhakat there is no need of `onbeforeunload` when you use `sessionStorage`, just set your user data in `sessionStorage` after login that's it. – Anshuman Jaiswal Jun 08 '18 at 12:20
-
hmmm, Right, happen, thnaks for your kind Info. it's another way to do some kind of. – Bishnu Kumar Bhakat Jun 08 '18 at 12:35
-
@BishnuKumarBhakat If this answer helped you, you can upvote/accept the answer. :) – Anshuman Jaiswal Jul 27 '18 at 09:25