cheeseybiscuits
cheeseybiscuits

Reputation: 51

Local Storage event won't fire in Chrome

I am trying to add an event listener that fires whenever data in local storage is changed. I have added the listener in my ComponentDidMount method like so:

componentDidMount() {
  window.addEventListener('storage', function(event) {
    console.log("Event");
    }
  );

But the event never seems to fire in Chrome (it fires in Firefox). I have tried it with two tabs, two windows, etc. Am I missing something? I thought that Chrome was able to support local storage functionality.

Upvotes: 4

Views: 2434

Answers (3)

Herohtar
Herohtar

Reputation: 5613

If you are testing this using local files, Chrome prevents local files (file:///*) from "talking" to each other by default as a security measure. You can disable this restriction by launching Chrome with the --allow-file-access-from-files flag:

chrome.exe --allow-file-access-from-files

Now the storage event should work as expected with local files.

Upvotes: 2

Mac
Mac

Reputation: 1566

You could always use a utility like localDataStorage to handle this for you, where events are fired in the same window/tab whenever a key value changes, such as those made by the set or remove methods. You can also use it to transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Once you instantiate the utility, the following snippet will allow you to monitor the events:

function localStorageChangeEvents( e ) {
    console.log(
        "timestamp: "     + e.detail.timestamp + " (" + new Date( e.detail.timestamp ) + ")" + "\n" +
        "key: "           + e.detail.key     + "\n" +
        "old value: "     + e.detail.oldval  + "\n" +
        "new value: "     + e.detail.newval  + "\n"
    );
};
document.addEventListener(
    "localDataStorage"
    , localStorageChangeEvents
    , false
);

Upvotes: 0

Matt Kruse
Matt Kruse

Reputation: 11

I was just researching this same problem and found an existing bug in Chrome when document.domain is set via script: https://bugs.chromium.org/p/chromium/issues/detail?id=136356

In this case, localStorage gets set, but the event is not fired.

Upvotes: 0

Related Questions