diceline-chartmagnifierquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

Workaround for storage event not triggering in the originator window

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