How to delete a localStorage item when the browser window/tab is closed?
Asked Answered
P

24

501

My Case: localStorage with key + value that should be deleted when browser is closed and not single tab.

Please see my code if its proper and what can be improved:

//create localStorage key + value if not exist
if (localStorage) {
  localStorage.myPageDataArr = {
    "name" => "Dan",
    "lastname" => "Bonny"
  };
}

//when browser closed - psedocode
$(window).unload(function() {
  localStorage.myPageDataArr = undefined;
});
Paryavi answered 30/3, 2012 at 12:44 Comment(5)
If you want to clear local storage upon browser close I would question your reasons for using it.Tyrosine
You can have both local and session storage objects- I would use sessionStorage for session values. Btw, setting a value to undefined does not delete it, or remove it from localStorage, it just sets its value to undefined.Perique
@Perique - Setting to undefined would overwrite the previously stored item though. But yes, using .removeItem() is more appropriate.Viral
just use sessionStorage instead of localStorageInternment
Use localStorage.clear(); if you want to clear whole storage.Mutualize
P
935

should be done like that and not with delete operator:

localStorage.removeItem(key);
Paryavi answered 22/5, 2012 at 20:54 Comment(7)
Why can't we use the delete operator, exactly? From my tests, it seems that delete localStorage.key works just as fine as localStorage.removeItem(key). It seems clearer to me to use delete when I set my variables like localStorage.key = 1 rather than localStorage.setItem('key', 1).Hypochromia
If it works, you can technically use it. But considering removeItem is provided as a member function, it seems logical to use it rather than running into potentially undefined behavior using a separate operator.Virgina
@Virgina keep in mind one can always (accidentally) do localStorage.removeItem = null;, making localStorage.removeItem(key); a potentially poor idea.Lachus
I don't see how that's a reasonable contingency to plan for. The fact that a language allows people to do destructive things doesn't mean you should adopt non-standard ways of using libraries as a defense against misuse of the language. If you or your fellow developers don't understand the difference between invocation and assignment, you have much larger problems than how best to remove items from localStorage.Virgina
@Lachus this is exactly why it's a bad idea to write localStorage.key = 1 in the first place - to avoid this kind of accidentsCorkscrew
$window.on('unload', function(){}) triggers upon tab close, so if I close a tab of my page, it will delete the local storage, which also being used in another tab. Is there any way to handle that? I know there is sessionStorage, however, it can only be used on one tab (Chrome and Firefox).Upgrowth
Docs for the method developer.mozilla.org/en-US/docs/Web/API/Storage/removeItemPortia
T
120

You should use the sessionStorage instead if you want the key to be deleted when the browser close.

Thaumatology answered 12/10, 2013 at 7:41 Comment(4)
This is the best answer; sessionStorage is the remedy for what the asker describes.Whopper
+1 for mentioning sessionStorage, but the W3C Editor's Draft says: 'The lifetime of a browsing context can be unrelated to the lifetime of the actual user agent process itself, as the user agent may support resuming sessions after a restart.'Yasui
Problem with 'sessionStorage' is that it is not stored when you open a new tab, for example with ctrl click a link. I need a localStorage/sessionStorage hybrid lol.Aragon
@EdwinStoteler Me too. I'm kinda confused what they were thinking when they designed it this way. I really need access essentially to an in-memory only browser storage that's destroyed when the browser closes. I want to store sensitive information in a way that can be accessed across an entire domain, but I don't want that info to hit any hard disks.Commeasure
U
116

Use with window global keyword:-

 window.localStorage.removeItem('keyName');
Undersurface answered 14/12, 2015 at 11:21 Comment(3)
why to use window Object ? simply localStorage.removeItem(key) works fine.Plectognath
check out this link #5320378Undersurface
Does this solution really works for IE 11 ? Please suggest. I am having this trouble in the angular 5 code.Samirasamisen
A
108

You can make use of the beforeunload event in JavaScript.

Using vanilla JavaScript you could do something like:

window.onbeforeunload = function() {
  localStorage.removeItem(key);
  return '';
};

That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action. I hope that solves your problem.

NOTE: The onbeforeunload method should return a string.

Aalto answered 17/7, 2012 at 21:7 Comment(6)
This was indeed useful. It might be nice to accept the answer (even after all this time).Hillel
@dhsto VanillaJS is plain JavaScript :) Look here: What is VanillaJS?.Longsighted
One problem is that this is called even if you navigate on the same page, not just when the tab is closed, which might not be what is intended. Side note: returning undefined from onbeforeunload will disable the message showing when unloading.Regolith
What happend if the user wants to stay on page and you already delete the local storage? Also the solution is not working on Chrome and IE11Floorboard
Why not use sessionStorage then?Sleepyhead
Note that this solution is not reliable and the item is deleted even if you don't confirm the close action. If the browser will crash or is closed improperly with a command like killall firefox, the item will not be deleted. If you are using sessionStorage instead of localStorage, when closing the browser completely and restoring the session, I also noticed that you have to prompt an alert box by returning a string because it will not have time to remove the item if you return undefined instead of ''. (tested with Firefox 62)Amberambergris
S
14
localStorage.removeItem(key);  //item

localStorage.clear(); //all items
Senatorial answered 29/11, 2019 at 17:1 Comment(1)
When answering an old question, your answer would be much more useful to other StackOverflow users if you included some context to explain how your answer helps, particularly for a question that already has an accepted answer. See: How do I write a good answer.Michelmichelangelo
M
13

There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help. The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining. If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried. In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser. I ended up using a custom code and logic that takes advantage of both.

I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened. This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'. At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab. Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab. So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh. Instead you need to store a flag in sessionStorage at every load before increasing the tab counter. Before storing this value, you can make a check to see if it already has a value and if it doesn't, this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.

Metaprotein answered 4/11, 2014 at 16:5 Comment(2)
As an answer to the "why not used sessionStorage?" approach, also from w3schools.com/html/html5_webstorage.asp : "window.sessionStorage - stores data for one session (data is lost when the tab is closed)". So the answer is just that. sessionStorage is useless if you want something persistent even in the usecase I described.Metaprotein
I am thinking the best implementation for this would be a browserWatcher service which basically fires events that other components can listen to (i.e. browser-open, browser-close, broswer-load, browser-unload etc. and hide all these implementation details inside it. Each component can decide which events it needs to handle in order to do its work. My only question would be what happens if power gets cut to the machine or something, then these properties would stay in localStorage next time the browser is opened wouldnt they?Uniformity
A
13

use sessionStorage

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.

The following example counts the number of times a user has clicked a button, in the current session:

Example

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Aspergillosis answered 26/6, 2015 at 10:53 Comment(2)
The data is deleted on browser tab close.Paulita
sessionStorage is not shared between tabs; it is not equal to localStorage.Coeternal
R
12

Try using

$(window).unload(function(){
  localStorage.clear();
});

Hope this works for you

Radian answered 30/3, 2012 at 13:6 Comment(1)
This will clean up entire localstorage. bad solution!Foreconscious
C
11

8.5 years in and the original question was never actually answered.

when browser is closed and not single tab.

This basic code snippet will give you the best of both worlds. Storage that persists only as long as the browser session (like sessionStorage), but is also shareable between tabs (localStorage).

It does this purely through localStorage.

function cleanup(){
    // place whatever cleanup logic you want here, for example:
    // window.localStorage.removeItem('my-item')
}

function tabOpened(){
    const tabs = JSON.parse(window.localStorage.getItem('tabs'))
    if (tabs === null) {
        window.localStorage.setItem('tabs', 1)
    } else {
        window.localStorage.setItem('tabs', ++tabs)
    }
}

function tabClosed(){
    const tabs = JSON.parse(window.localStorage.getItem('tabs'))
    if (tabs === 1) {
        // last tab closed, perform cleanup.
        window.localStorage.removeItem('tabs')
        cleanup()
    } else {
        window.localStorage.setItem('tabs', --tabs)
    }
}

window.onload = function () {
    tabOpened();
}

window.onbeforeunload = function () {
    tabClosed();
}

Coeternal answered 15/10, 2020 at 10:46 Comment(2)
I don't think this works correctly. Think of this scenario: First, the user goes to the home page of the site. Now tabs is set to 1. Then the user clicks a link and navigates to another page on the site => The onbeforeunload handler is called which cleans the localStorage.Pupiparous
I see your point; I've been working with SPAs too long... I'm afk at the moment, but I'll update the answer when I get home.Coeternal
C
10

There are five methods to choose from:

  • setItem(): Add key and value to localStorage
  • getItem(): Retrieve a value by the key from localStorage
  • removeItem(): Remove an item by key from localStorage
  • clear(): Clear all localStorage
  • key(): Passed a number to retrieve nth key of a localStorage

You can use clear(), this method when invoked clears the entire storage of all records for that domain. It does not receive any parameters.

window.localStorage.clear();
Cantonment answered 20/2, 2020 at 19:28 Comment(0)
P
9
for (let i = 0; i < localStorage.length; i++) {
    if (localStorage.key(i).indexOf('the-name-to-delete') > -1) {
        arr.push(localStorage.key(i));
    }
}

for (let i = 0; i < arr.length; i++) {
    localStorage.removeItem(arr[i]);
}
Prognostic answered 17/5, 2018 at 10:50 Comment(0)
L
6

This will do the trick for objects.

localStorage.removeItem('key');

Or

localStorage.setItem('key', 0 );  
Larch answered 4/10, 2021 at 3:30 Comment(0)
P
4

why not used sessionStorage?

"The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window."

http://www.w3schools.com/html/html5_webstorage.asp

Psychrometer answered 15/12, 2014 at 16:25 Comment(0)
A
4

Although, some users already answered this question already, I am giving an example of application settings to solve this problem.

I had the same issue. I am using https://github.com/grevory/angular-local-storage module in my angularjs application. If you configure your app as follows, it will save variable in session storage instead of local storage. Therefore, if you close the browser or close the tab, session storage will be removed automatically. You do not need to do anything.

app.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
  .setPrefix('myApp')
  .setStorageType('sessionStorage')
});

Hope it will help.

Anabranch answered 13/12, 2016 at 13:25 Comment(0)
R
3

Here's a simple test to see if you have browser support when working with local storage:

if(typeof(Storage)!=="undefined") {
  console.log("localStorage and sessionStorage support!");
  console.log("About to save:");
  console.log(localStorage);
  localStorage["somekey"] = 'hello';
  console.log("Key saved:");
  console.log(localStorage);
  localStorage.removeItem("somekey");  //<--- key deleted here
  console.log("key deleted:");
  console.log(localStorage);
  console.log("DONE ===");
} else {
  console.log("Sorry! No web storage support..");
}

It worked for me as expected (I use Google Chrome). Adapted from: http://www.w3schools.com/html/html5_webstorage.asp.

Rabbin answered 18/4, 2013 at 16:24 Comment(0)
E
3

I don't think the solution presented here is 100% correct because window.onbeforeunload event is called not only when browser/Tab is closed(WHICH IS REQUIRED), but also on all other several events. (WHICH MIGHT NOT BE REQUIRED)

See this link for more information on list of events that can fire window.onbeforeunload:-

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

Elnaelnar answered 8/7, 2013 at 20:34 Comment(1)
You may be right, but still what you've posted is a comment, not an answer.Viral
R
3

After looking at this question 6 years after it was asked, I found that there still is no sufficient answer to this question; which should achieve all of the following:

  • Clear Local Storage after closing the browser (or all tabs of the domain)
  • Preserve Local Storage across tabs, if at least one tab remains active
  • Preserve Local Storage when reloading a single tab

Execute this piece of javascript at the start of each page load in order to achieve the above:

((nm,tm) => {
    const
            l = localStorage,
            s = sessionStorage,
            tabid = s.getItem(tm) || (newid => s.setItem(tm, newid) || newid)((Math.random() * 1e8).toFixed()),
            update = set => {
                let cur = JSON.parse(l.getItem(nm) || '{}');
                if (set && typeof cur[tabid] == 'undefined' && !Object.values(cur).reduce((a, b) => a + b, 0)) {
                    l.clear();
                    cur = {};
                }
                cur[tabid] = set;
                l.setItem(nm, JSON.stringify(cur));
            };
    update(1);
    window.onbeforeunload = () => update(0);
})('tabs','tabid');

Edit: The basic idea here is the following:

  1. When starting from scratch, the session storage is assigned a random id in a key called tabid
  2. The local storage is then set with a key called tabs containing a object those key tabid is set to 1.
  3. When the tab is unloaded, the local storage's tabs is updated to an object containing tabid set to 0.
  4. If the tab is reloaded, it's first unloaded, and resumed. Since the session storage's key tabid exists, and so does the local storage tabs key with a sub-key of tabid the local storage is not cleared.
  5. When the browser is unloaded, all session storage will be cleared. When resuming the session storage tabid won't exists anymore and a new tabid will be generated. Since the local storage does not have a sub-key for this tabid, nor any other tabid (all session were closed), it's cleared.
  6. Upon a new created tab, a new tabid is generated in session storage, but since at least one tabs[tabid] exists, the local storage is not cleared
Rabideau answered 7/9, 2018 at 11:12 Comment(1)
If the browser crash, however, the window.onbeforeunload won't be called, and the local tabs[tabid] will not be set to 0 => the local storage will never be cleared anymore. I think a watchdog would be more appropriate in that case, instead of writing 1 upon tab loading, you should write current timestamp. Then in the reduce part, you should assert the delay since that timestamp is not too big or replace by 0 if it is. That way, you don't depend on actual call of onbeforeunload. The tab just need to reset the watchdog from time to time to maintain the local storage existence.Rycca
U
2

You can simply use sessionStorage. Because sessionStorage allow to clear all key value when browser window will be closed .

See there : SessionStorage- MDN

Uncoil answered 21/1, 2020 at 6:17 Comment(0)
R
1

This is an old question, but it seems none of the answer above are perfect.

In the case you want to store authentication or any sensitive information that are destructed only when the browser is closed, you can rely on sessionStorage and localStorage for cross-tab message passing.

Basically, the idea is:

  1. You bootstrap from no previous tab opened, thus both your localStorage and sessionStorage are empty (if not, you can clear the localStorage). You'll have to register a message event listener on the localStorage.
  2. The user authenticate/create a sensitive info on this tab (or any other tab opened on your domain).
  3. You update the sessionStorage to store the sensitive information, and use the localStorage to store this information, then delete it (you don't care about timing here, since the event was queued when the data changed). Any other tab opened at that time will be called back on the message event, and will update their sessionStorage with the sensitive information.
  4. If the user open a new tab on your domain, its sessionStorage will be empty. The code will have to set a key in the localStorage (for exemple: req). Any(all) other tab will be called back in the message event, see that key, and can answer with the sensitive information from their sessionStorage (like in 3), if they have such.

Please notice that this scheme does not depend on window.onbeforeunload event which is fragile (since the browser can be closed/crashed without these events being fired). Also, the time the sensitive information is stored on the localStorage is very small (since you rely on transcients change detection for cross tab message event) so it's unlikely that such sensitive information leaks on the user's hard drive.

Here's a demo of this concept: http://jsfiddle.net/oypdwxz7/2/

Rycca answered 16/1, 2019 at 16:50 Comment(2)
Thank you for the edit xryl669, you made a good point. When I am now thinking about this, would it perhaps be best to use a shared web worker? developer.mozilla.org/en-US/docs/Web/API/SharedWorker in case current browser support is not an issueRabideau
Yes, you can use either a SharedWorker or a BroadcastChannel (or a localStorage like this), although the first two are not available in Edge. Basically, any method that's cross tab, cross window, would work. The difficulty is finding one that works everywhere with the minimum of hassle.Rycca
B
1

There are no such the way to detect browser close so probably you can't delete localStorage on browser close but there are another way to handle the things you can uses sessionCookies as it will destroy after browser close.This is I implemented in my project.

Bedard answered 21/8, 2019 at 12:0 Comment(0)
G
0
    if(localStorage.getItem("visit") === null) {
      localStorage.setItem('visit', window.location.hostname);
      console.log(localStorage.getItem('visit'));
    } 
      else if(localStorage.getItem('visit') == 'localhost'){
            console.log(localStorage.getItem('visit'));
      }
    else {
     console.log(localStorage.getItem('visit'));
    }
   $(document).ready(function(){
      $("#clickme").click(function(){
         localStorage.setItem('visit', '0');
      });
   });  
   window.localStorage.removeItem('visit');
Gwenette answered 26/6, 2021 at 5:39 Comment(1)
Welcome to Stackoverflow! Can you add an explaination to code please?Township
T
0
window.addEventListener('beforeunload', (event) => {

    localStorage.setItem("new_qus_id", $('.responseId').attr('id'));

    var new_qus_no = localStorage.getItem('new_qus_id');
    console.log(new_qus_no);

});

if (localStorage.getItem('new_qus_id') != '') {
    var question_id = localStorage.getItem('new_qus_id');
} else {
    var question_id = "<?php echo $question_id ; ?>";
}
Trident answered 10/7, 2021 at 5:20 Comment(1)
Welcome to Stackoverflow! Can you add an explaination to code please?Silicium
P
0

You can use session storage for this purpose. data which store in session storage it will remove automatically when browser is close.

You can manually delete session storage as well by following command.

sessionStorage.removeItem("key");

for clear all

sessionStorage.clear()

Petal answered 3/7, 2023 at 13:49 Comment(0)
U
-7

you can try following code to delete local storage:

delete localStorage.myPageDataArr;
Ukase answered 30/3, 2012 at 14:26 Comment(7)
This is not the right way of deleting a localStorage key. You should use localStorage.removeItem(key); to delete a key.Aalto
Should use localStorage.removeItem(key); not the delete keyword.Abirritate
@Aalto Why not using delete? I tried, and it works. Is there any side effect or anything that we should not use delete? Thank you.Footstep
@Footstep using delete is not best practice in localStorageIvonneivor
@Ivonneivor That's a not-answerMateusz
Using delete, you're deleting the key in the memory version of the localStorage. localStorage is usually backed by the hard drive, and using delete does not remove the data from the hard drive (at least, not on firefox). Using removeItem actually performs real cleanup since there is native code being called here. You can check this with firefox by looking at your profile folder.Rycca
@Rycca using the delete operator works perfectly, if you know what I mean as long as your browser suppors the localStorage API. It's not about how the data is physically stored. using the removeItem() method does not mean it directly operates your physical storage. A computer is designed to use the memory for all operations.Stative

© 2022 - 2024 — McMap. All rights reserved.