How to subscribe on localStorage but not on sessionStorage events - javascript

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

Related

Is there a way to force a PWA to stay in offline mode via a toggle in-app?

Recently just started building a PWA and I thought a useful feature for privacy and control could be a toggle on the site that allows the user to force the site to remain in offline mode until the toggle is pressed again. After some research, however, I am unable to find any way to accomplish this, anybody has any ideas? Thanks in advance.
Create a toggle or checkbox on in the HTML from where you will control the state. This input element will control wether offline mode is on or off. The value of that input has to be send to the service worker who then can decide what to do whenever a fetch request is being made.
<input id="check-offline" type="checkbox" name="offline-mode">
<label for="check-offline">Offline mode</label>
In your main thread select the button and register your Service Worker. Whenever the worker has registered successfully add an event listener to the input you've created up here and listen for a change. In the handler of the event listener use the postMessage function on the worker to send the checked value to the worker.
const offLineToggle = document.getElementById('check-offline');
navigator.serviceWorker.register('/path/to/service-worker.js').then(registration => {
const serviceWorker = registration.active;
if (serviceWorker !== null) {
offLineToggle.addEventListener('change', event => {
serviceWorker.postMessage({
name: 'offlineMode',
value: event.target.checked
});
});
}
});
Then in your Service Worker script create an object (or variable) to store the current settings in. In the ServiceWorkerGlobalScope listen for the message event. This is the receiving end for the postMessage function. Here you can handle the data and update the settings for the offlineMode.
Then add another event listener and listen for the fetch event, which will be fired whenever a fetch request has been made from the main thread. In the event handler check if the offline mode is on or off and handle accordingly.
const settings = {
offlineMode: false
};
self.addEventListener('message', { data } => {
const { name, value } = data;
if (settings.hasOwnProperty(name)) {
settings[name] = value;
}
});
self.addEventListener('fetch', event => {
const { offlineMode } = settings;
if (offlineMode === true) {
// Force return data from cache.
} else {
// Get fresh data from the server.
}
});
This all is an outline of how it could work. Read up on the Using Service Workers article on MDN to see how you can access the cache and control the data that is being send to the client.
Service workers have access to indexedDB. Alternatively, DOM has access to the cache storage.
You could cache a key "offline" either in indexedDB or cache storage, and check the value on the fetch event.

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

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

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 push oath token to LocalStorage or LocalSession and listen to the Storage Event? (SoundCloud Php/JS bug workaround)

This references this issue: Javascript SDK connect() function not working in chrome
I asked for more information on how to resolve with localstorage and was asked to create a new topic.
The answer was "A workaround is instead of using window.opener, push the oauth token into LocalStorage or SessionStorage and have the opener window listen to the Storage event."
but i have no idea how to do that. It seems really simple, but i don't know where to start. I couldn't find an relevant examples.
You can attach an event listener to the "storage" event which is fired by the window.
window.addEventListener("storage", myHandler, false);
The handler is passed an event object which includes the key which changed.
function myHandler(event) {
if (event.key === 'the_oauth_token') {
// do something with it
}
}
Here's a demo: http://html5demos.com/storage-events

Categories