How to remove and clear all localStorage data [duplicate] - javascript

This question already has answers here:
Clearing localStorage in javascript?
(14 answers)
Closed 8 years ago.
I need to clear all data i set into localStorage. By this, I mean completely reset localStorage to null when users remove their accounts.
How can i do that with a simple function?
I tried this:
function clearLocalStorage(){
return localStorage= null;
}
But it doesn't work as expected.

localStorage.clear();
should work.

If you want to remove/clean all the values from local storage than use
localStorage.clear();
And if you want to remove the specific item from local storage than use the following code
localStorage.removeItem(key);

It only worked for me in Firefox when accessing it from the window object.
Example...
window.onload = function()
{
window.localStorage.clear();
}

Using .one ensures this is done only once and not repeatedly.
$(window).one("focus", function() {
localStorage.clear();
});
It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.
.one is especially useful when you want local storage to be cleared only once the first time a web page is opened or when a mobile application is installed the first time.
// Fired once when document is ready
$(document).one('ready', function () {
localStorage.clear();
});

Something like this should do:
function cleanLocalStorage() {
for(key in localStorage) {
delete localStorage[key];
}
}
Be careful about using this, though, as the user may have other data stored in localStorage and would probably be pretty ticked if you deleted that. I'd recommend either a) not storing the user's data in localStorage or b) storing the user's account stuff in a single variable, and then clearing that instead of deleting all the keys in localStorage.
Edit: As Lyn pointed out, you'll be good with localStorage.clear(). My previous points still stand, however.

Related

How to make the user not duplicate browser tabs?

There was a task to make each web page of the project not repetitive. Those. the user should not, as a consequence of inattention within the same browser, open multiple duplicates of the same web page. Please suggest a specific solution.
The task can be solved very simply, if one condition is met — each page has its own unique identifier. I have this $(‘body’).attr (‘id’).
Let’s call the function noDuplicateTabs and call it every time the page starts.
We use localStorage:
let noDuplicateTabs = function (pageName) {
localStorage.getItem(pageName)
? window.close()
: localStorage.setItem(pageName, 'open');
window.onbeforeunload = function () {
localStorage.setItem(pageName, '');
};
}
Thus, we pass the name of the page in the function, check for the presence of a value using the localStorage key corresponding to the page name.
If a key with a non-empty value is found, then we close the page, if not, then write the value to it ‘open’.
We also use the onbeforeunload property of the window, which works before reloading or closing the page. In this case, we will erase the value.
Now there will be no duplicates within the same browser.

Remove local storage when the window is closed Angular 2

Once the user is logged in, am maintaining user token in local storage and its is available across all the tabs and once the user close the window, I need to remove the user token from the local storage.
How can I remove local storage when the browser/window/Tab is closed?
Found this tip somewhere a while ago. You can store your data to localStorage for a couple of seconds and add an event listener for a storage event. By doing this, you will know when any of the tabs wrote something to your localStorage and you can copy its content to the sessionStorage, then just clear the localStorage afterwards
Got It!
Just I added the below code in app.component.ts file to remove all local storage data when the window is closed.
import { HostListener } from '#angular/core';
#HostListener('window:beforeunload', ['$event'])
public beforeunloadHandler($event) {
localStorage.removeItem('UserToken');
}
window.addEventListener("unload", function(event) {
//Use any of local storage methods to remove the user.
localStorage.removeItem('key'); // key you want to be removed.
//OR
localStorage.clear();
});
// You can also try using.
window.addEventListener("unload", function(event) { localStorage.removeItem('key'); });
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onunload
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Run window.addEventListener('load' ...) only once

I am wondering if there is any way to run window.addEventListener('load' ...) only the first time the specific page is loaded.
I tried just setting a flag called loaded to false, and only run the code inside the eventListener if loaded === false. Then once it's run, I set loaded to true. But does not work, still runs every time.
Can I perhaprs remove the eventListener once its run?
Keep a localStorage item that contains an array corresponding to all pages that have been loaded so far. Only attach the listener if that page isn't stored in localStorage yet. For example:
const { href } = window.location;
const alreadyLoaded = JSON.parse(localStorage.loaded || '[]');
if (!alreadyLoaded.includes(href)) {
alreadyLoaded.push(href);
localStorage.loaded = JSON.stringify(alreadyLoaded);
window.addEventListener('load', () => {
// rest of your code
});
}
Set the once property to true and it will run only once (doesn't work with Internet explorer)
More information here
const once = {
once : true
};
window.addEventListener('load',callback, once);
Easy way: you can use web storage that is if it's supported. Something like:
if (!localStorage.getItem("listenerLoaded")) {
window.addEventListener('load'...)
localStorage.setItem("listenerLoaded", true);
}
A bit tedious work would be using:
2. cookie(still browser needs support etc).
3. ajax and hold session
No it is not possible a a new execution context will be created every time that page loads.
You can try something like localStorage to save the state.
LocalStorage API helps you to save data which can be accessed later.it is an Object which can be used to access the current origin's local storage space.
For more info visit:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Simply set a value in local storage once listener gets loaded then read that value before adding it again.
if (!localStorage.getItem("isLoaded")) {
window.addEventListener('load' ...)
localStorage.setItem("isLoaded", true);
}
Using removeEventListener is a good option:
var callback = function(){
...
}
window.removeEventListener('load',callback);
window.addEventListener('load',callback);

Updating localstorage with button click

I need to update single item of object in localstorage without reloading page.
jsFiddle: https://jsfiddle.net/7xsg8679/
Here is my code:
if (obj.isCompletedTask === false) {
newDone.innerHTML = "Not done";
newDone.dataset.done = false;
newButton.addEventListener('click', function (e) {
newDone.innerHTML = "Done";
newDone.dataset.done = true;
newUl.style.backgroundColor = "red";
e.preventDefault();
})
}
If I use if(obj.isCompletedTask === true) in the if-statement - it does nothing. Why?
When you use obj.isCompletedTask === true the button does nothing isCompletedTask is false, so the code between curly brackets { ... } is not run at all, so the eventListener does not get attached to your button click event.
You may want to move your if statement to inside of event listener, if i understood your intentions correctly.
When you want to update an element in localstorage, you do it like that:
localStorage.setItem('list', JSON.stringify(tasks));
...but when your tasks object changes, you need to keep a track of that yourself, and manually update localStorage. This relation is called data-binding. Moreover, you cannot just update subelement of your tasks directly, you have to replace list in localStorage with fresh version of tasks every time something in tasks changes.`
General remark: from what i see in your fiddle, i do really think you should have a look at some framework (like vue, react or angular). Keeping track of the changes here and there will really be tiresome after a while and besides, why should yo reinvent the wheel?

Simple function using a lot of memory

I'm using local storage because after the click, the page reloads, so I can keep track of the last item clicked.
As you can see, I've tried to clear localStorage in order to shrink the memory in use, but it's already at 1.000.000K in less then 10 minutes of usage.
Is this script redeclaring this variables at different location everytime my page reloads?
What is happening that is making it use so mant memory?
This is my entire code.
It's an extension I'm creating for chrome, it selects an option and clicks the button, the button submits a form, the page reload, and it does eveything again and again.
var last = localStorage.getItem('last');
var current = getNext(last);
var prox = getNext(current);
localStorage.clear();
$('select[name="myselect"] option').each(function(){
if($(this).val().indexOf(current)>-1){
$(this).prop('selected', true);
$('.abc').first().click();
localStorage.setItem('last',current);
}
});
function getNext(current){
var arrIds = ['227','228','229','230','231','232'];
return arrIds[arrIds.indexOf(current)+1] || '227';
}
Updated code, without var declarations, that has decreased memory consumption drastically, but with time, the memory raises (in ten minutes went from 160.000K to 240.000K):
$('select[name="myselect"] option').each(function(){
if($(this).val().indexOf(getNext(localStorage.getItem('last')))>-1){
$(this).prop('selected', true);
$('.abc').first().click();
localStorage.setItem('last',getNext(localStorage.getItem('last')));
}
});
function getNext(current){
var arrIds = ['227','228','229','230','231','232'];
return arrIds[arrIds.indexOf(current)+1] || '227';
}
As per the discussion in the comments below the question, the issue appears to come from jQuery itself. The exact reason isn't known at this point, but it appears jQuery has retained data that is not being released when the form is submitted.
This probably has to do in part with some aspect of it being a Chrome extension, since typically on a refresh, the browser would release all memory including globals.
jQuery creates great potential for memory leaks by holding data and closures in a global reference called jQuery.cache. If this is not cleaned up properly, leaks abound.
Since you're creating a Chrome extension, there shouldn't be much to compel you to use jQuery, since you'll not need to worry about browser incompatibility from browsers like IE6 and 7. By using the DOM API directly without such dependencies, the overall code will be smaller and much faster.

Categories