[javascript] How to delete a localStorage item when the browser window/tab is closed?

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;
});

This question is related to javascript jquery html local-storage

The answer is


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


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.


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

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


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.";

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.


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.


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(){
    // whatever cleanup logic you want
    window.localStorage.clear();
    window.sessionStorage.clear();
}

window.onbeforeunload = function () {
    let tabs = JSON.parse(window.localStorage.getItem('tabs'))
    if (tabs === 1) {
        // last tab closed, perform cleanup.
        cleanup();
    } else {
        window.localStorage.setItem('tabs', --tabs);
        window.dispatchEvent(new Event('storage'));
    }
}

window.onstorage = function () {
    console.log(JSON.parse(window.localStorage.getItem('tabs')));
};

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

Try using

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

Hope this works for you


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.


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();

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]);
}

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/


localStorage.removeItem(key);  //item

localStorage.clear(); //all items

you can try following code to delete local storage:

delete localStorage.myPageDataArr;

Use with window global keyword:-

 window.localStorage.removeItem('keyName');

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.


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


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

See there : SessionStorage- MDN


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to local-storage

Angular 6: saving data to local storage Is it safe to store a JWT in localStorage with ReactJS? How to save to local storage using Flutter? Setting and getting localStorage with jQuery Local storage in Angular 2 How to store token in Local or Session Storage in Angular 2? QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota What is the difference between localStorage, sessionStorage, session and cookies? How to save an image to localStorage and display it on the next page? Can local storage ever be considered secure?