简体   繁体   中英

Detect any change in localStorage?

Is there any way to detect any change in HTML5 localStorage and then call certain functions if there is any change indeed? I have certain keys stored with names as "e1", "e2", "e3", and so on...

i want to detect if any key is removed or added and then trigger some functions if there is any change...

According to specs Storage interface emits storage event on global objects which it affects.

So in your case you may just add handler

window.addEventListener("storage", function () {
    // do your checks to detect
    // changes in "e1", "e2" & "e3" here
}, false);

There is no need for jQuery even.

The localDataStorage interface (a handy wrapper for the HTML5 localStorage API) conveniently fires change events on the same page/tab/window in which the storage event occurred. Disclaimer: I am the author of the interface.

Once you install localDataStorage , this sample code will let you see those change events:

function nowICanSeeLocalStorageChangeEvents( e ) {
    console.log(
        "subscriber: "    + e.currentTarget.nodeName + "\n" +
        "timestamp: "     + e.detail.timestamp + " (" + new Date( e.detail.timestamp ) + ")" + "\n" +
        "prefix: "        + e.detail.prefix    + "\n" +
        "message: "       + e.detail.message   + "\n" +
        "method: "        + e.detail.method    + "\n" +
        "key: "           + e.detail.key       + "\n" +
        "old value: "     + e.detail.oldval    + "\n" +
        "new value: "     + e.detail.newval    + "\n" +
        "old data type: " + e.detail.oldtype   + "\n" +
        "new data type: " + e.detail.newtype
    );
};
document.addEventListener(
    "localDataStorage"
    , nowICanSeeLocalStorageChangeEvents
    , false
);

The example nowICanSeeLocalStorageChangeEvents() function just spits out key details, but you could easily use it to take specific actions like you mentioned.

For example, if you add a new key

lds.set( 'e2', 101 );

then you'll get something like

message: create new key
method: set
key: e2
old value: undefined
new value: 101
old data type: undefined
new data type: integer

When you delete a key

lds.remove( 'e2' );

then you'll see something like

message: remove key
method: remove
key: e2
old value: 101
new value: undefined
old data type: integer
new data type: undefined

so you can easily respond to local storage key events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM