I want to write a function to listen to sessionStorage. I found that the following code works fine on both computers and Android phones, but it suddenly stopped working on iOS phones recently. Does anyone know how to fix it?
var Watch_Storage = function () {
var originalSetItem = sessionStorage.setItem;
sessionStorage.setItem = function (key, value) {
let event = new Event("setItemEvent");
event.key = key;
event.newVal = value;
window.dispatchEvent(event);
originalSetItem.apply(this, arguments);
}
};
var setItemEventHandler = function (e) {
console.log(e.newVal);
},
Watch_Storage();
window.addEventListener("setItemEvent", function (e) {
setItemEventHandler(e);
});
I tried rewriting it as document.addEventListener, but it still doesn't work. Currently, the only solution I can think of is to temporarily use setInterval to periodically fetch new data when detecting iOS. I can't think of any other solutions.
sessionStorage.setItem()
method is called ? (after the listener is registered)document.addEventListener
for an event clearly dispatched fromwindow
?console.log
inside your code near thewindow.dispatchEvent
to see if yoursetItem
is being called at all