LocalStorage Events - macmcmeans/localDataStorage GitHub Wiki

Native localStorage will not listen for change events fired from the same tab/page making the change, but fires only when the "storage area has been modified in the context of another document." Depending on your design, this built-in drawback can be debilitating, but localDataStorage easily decimates this typical roadblock by dispatching custom events to deliver the pertinent details.

The localDataStorage interface fires on storage key value changes, such as those made by the set or remove methods. The event returns an activity timestamp and message, as well as expected specifics regarding the affected key(s). The old and new key value data types are also reported.

The following code shows everything the event reports:

// the function to call to catch emitted data
const nowICanSeeLocalStorageChangeEvents = function( e ) {
    console.log(
        "subscriber: " + e.currentTarget.nodeName + "\n" +
        "date: "       + e.detail.date            + "\n" +
        "timestamp: "  + e.detail.timestamp       + "\n" +
        "prefix: "     + e.detail.prefix          + "\n" +
        "message: "    + e.detail.message         + "\n" +
        "method: "     + e.detail.method          + "\n" +
        "old key: "    + e.detail.oldkey          + "\n" +
        "new key: "    + e.detail.newkey          + "\n" +
        "old value: "  + e.detail.oldval          + "\n" +
        "new value: "  + e.detail.newval          + "\n" +
        "old type: "   + e.detail.oldtype         + "\n" +
        "new type: "   + e.detail.newtype         + "\n" +
        "old base: "   + e.detail.oldbase         + "\n" +
        "new base: "   + e.detail.newbase
    );
}

// attach an event listener to our custom event
document.addEventListener(
    "localDataStorage"
    , nowICanSeeLocalStorageChangeEvents
    , false
);

The following methods may trigger a change event: chopget, clear, copy, forceset, remove, rename, safeset, set and softset.

📝 NOTE: By default, this data is also broadcast across the origin.