Remove local storage when the window is closed Angular 2 - javascript

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

Related

Reload all open tabs on localStorage item change javascript

I want to reload the pages of a particular site on all the open tabs when the value in the local Storage changes. How can I achieve this?
You can subscribe to storage events like this:
window.addEventListener('storage', function(e) {
// Some storage value changed. Reload tab!
});
As noted in the linked documentation:
The storage event of the Window interface fires when a storage area (localStorage or sessionStorage) has been modified in the context of another document.
Do note this is limited to tabs which have access to the same local storage (limited by the domain of the website).
Here is a solution to refresh all using the same Angular Application
Step 1: Make a list of all Opened Tabs With a unique ID.
const myTab = sessionStorage.tabID ? sessionStorage.tabID: Math.random();
let tabList = JSON.parse(localStorage.getItem('tabList'));
if(!tabList) tabList = {};
tabList[myTab] = { refresh: false, updated_ts: new Date() };
localStorage.setItem('tabList', JSON.stringify(tabList));
Step 2: Monitor Activity in local storage. [This can be done in a number of ways]
setInterval(function(){
let tabList = JSON.parse(localStorage.getItem('tabList'));
if(tabList && tabList[myTab] && tabList[myTab].refresh){
delete tabList[myTab];
localStorage.setItem('tabList', JSON.stringify(tabList));
console.log("Do refesh");
// location.reload();
}
else{
console.log("Don't refesh");
}
}, 3000);
OR (Subscribe to storage events)
window.addEventListener('storage', function(e) {
// Your logic
});
Step 3: Trigger Refresh
function triggerRefesh() {
let tabList = JSON.parse(localStorage.getItem('tabList'));
if(tabList) for (const tabID in tabList) tabList[tabID].refesh = true;
localStorage.setItem('tabList', JSON.stringify(tabList));
}
Note: You should not reload an angular application, rather route to your authentication page or refresh your component

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

How can I clear the localstorage when user close react application window?

I am developing a react-redux application where once the user logs in, I was to store some information about the user in local storage. This is so that I can easily retrieve the user information when they perform a action.
If the user close the browser window, I would like to clear all localstorage for the react application. How can I achieve that?
You can just use the JS function :
localStorage.clear();
Firing the event on close of the window
window.onbeforeunload = function() {
localStorage.clear();
}
You could consider using Window.sessionStorage instead of Window.localStorage.
Data stored in sessionStorage gets cleared when the page session ends. A page
session lasts for as long as the browser is open and survives over
page reloads. Source.
You can use localStorage.clear but you have to watch for window close event. Another possible solution is you can use session storage so it will be available until your browser is open. After that session will be removed, so you don't need to do anything.
To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close.
window.onunload = () => {
// Clear the local storage
window.MyStorage.clear()
}
You can make use of the NPM package react-beforeunload
Implementing react-beforeunload on NextJS (Typescript)
On your main file (in NextJS world: _app.tsx) do the following:
...
import { Beforeunload } from 'react-beforeunload';
const removeApplicationData = () => {
if (window) { // NextJS is ServerSideRendering, therefore the window-check.
localStorage.clear();
}
};
...
return (
<Beforeunload onBeforeunload={removeApplicationData}>
<Component {...pageProps} />
</Beforeunload>
);

How to subscribe on localStorage but not on sessionStorage events

As far as I understand:
window.addEventListener('storage', function(event){
...
}, false);
is subscription on both localStorage and sessionStorage events.
Can I subscribe on localStorage events only?
Thanks.
I don't think you can, as you say storage is fired on the window when any storage item changes. You just have to check the storageArea property of the event when you receive it, and ignore the ones from session storage. E.g.:
window.addEventListener('storage', function(event){
if (event.storageArea === localStorage) {
// It's local storage
}
}, false);

How to remove and clear all localStorage data [duplicate]

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.

Categories