-1

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.

6
  • 1
    Use document.addEventListener instead. Commented Jul 8 at 11:08
  • @YashMaheshwari he said he tried it too
    – Elikill58
    Commented Jul 8 at 11:12
  • 1
    @Nico are you sure the sessionStorage.setItem() method is called ? (after the listener is registered)
    – Elikill58
    Commented Jul 8 at 11:13
  • @YashMaheshwari why would you document.addEventListener for an event clearly dispatched from window? Commented Jul 8 at 11:17
  • What I would do is put a console.log inside your code near the window.dispatchEvent to see if your setItem is being called at all Commented Jul 8 at 11:21

0