Listen only to localStorage.removeItem ()

I show notifications to users using the pnotify plugin. However, I want to delete the notification for all tabs if the user closes the notification on tab 1 by clicking the X icon.

I use localstorage for this, every time a new notification is displayed to the user, it is added to localStorage. When the user clicks the X icon, I do localStorage.removeItem(key) . How to listen to this event to close the notification on all tabs?

My listener is below:

 $(window).bind('storage', function(e) { // if it was removed if (e.originalEvent.newValue == null) { var notificationObject = e.originalEvent.oldValue; // call remove function on pnotify object notificationObject.remove(); } }); 

I noticed that newValue turns to null if it was removed, this will theoretically work (not yet verified), but is it reliable in terms of whether it always returns null if removeItem was called to this element? What if the element value changes to null , it will trigger this event, since the value has changed correctly?

+6
source share
2 answers
 $(window).on("itemRemoved", function(e, args) { console.log(e, args); if (!localStorage.getItem(args)) { // do stuff } }) fn = localStorage.removeItem; localStorage.removeItem = function() { var args = arguments; setTimeout(function() { $(window).trigger("itemRemoved", [args[0]]) }); return fn.call(localStorage, args[0]); } 
+2
source

Local storage saves everything as a string.

 localStorage.setItem("foo", null); // returns "null" localStorage.getItem("foo"); 

And indeed, newValue null when it is deleted. MDN: StorageEvent says:

The new key value. newValue null when the change was caused by the clear() storage method or key was removed from the repository. Only for reading.

Therefore, it is safe to check for null with === null .

+3
source

All Articles