LocalStorage event not triggering

Whenever a value is set in localStorage, a ```storage``` event will be dispatched on all other windows from the same origin. The event is not fired or catchable in the originator ```window``` when it is modified through a script.

This was a problem because I wanted to be able to have an ```Elm subscription``` as the only source of truth for my session.

In order to achieve this, I'm mimicking the storage event from within the command port as soon as the message is received through the port.

```
app.ports.commandPort.subscribe(session => {
  localStorage.session = JSON.stringify(session);
  app.ports.subscriptionPort.send(localStorage.session);
});
```

```
window.addEventListener(
    "storage",
    event => {
      if (event.storageArea === localStorage && event.key === "session") {
        app.ports.subscriptionPort.send(event.newValue);
      }
    },
    false
);
```

And in Elm: 

```
port subscriptionPort : (Encode.Value -> msg) -> Sub msg
```

```
port commandPort : Maybe Encode.Value -> Cmd msg
```

Nick Ciolpan
11 Aug 2020
« Back to post