Question

Is there any way to intercept calls to localStorage? Or maybe some handlers exists?

If I have somewhere in code script like localStorage.getItem() I need to know that storage going to get some item, and I want to prevent this, and do something I need.

I want to write a framework for a mobile web developers. I want them to use localstorage calls in usual way. My framework will intercept this calls and will put data not to W3C storage, but to native device storage. Is that possible? Thanks.

Was it helpful?

Solution

You can use prototypes. Try something like that:

 Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function (key, value)
        {
            alert("works");
        }

    localStorage.setItem("A", "A");

If you'll need farther clarification feel free to ask.

OTHER TIPS

You can track changes to localStorage and sessionStorage with the storage event, fired on window-

The event is fired on all open tabs or pages from the same origin.

function storageHandler(e){
    var info={
        key:e.key, oldV:e.oldValue, newV:e.newValue, url:e.url || e.uri
    };
    //do something with info
}
window.addEventListener('storage', storageHandler, false);

special storage event properties:

key- the named key that was added, removed, or modified
oldValue- the previous value(now overwritten), or null if a new item was added
newValue-the new value, or null if an item was removed
url or uri-     the page which called a method that triggered this change

You may need to test for IE below#9(attachEvent and global event handling) and localStorage support.

You can replace the entire localStorage variable with your own although you may not be able to replicate every part of the API...

var localStorage = (function () {
    return {
        setItem: function (key, value) {
            alert(key);
        }
    };
}());

localStorage.setItem('a', 'b');

You will need to implement the same interface so your code invisibly slots in, but this example with setItem shows you how to do it all.

You can still call the old localStorage if you pop it into a variable to keep hold of it.

I haven't implemented whatever condition you're going to test to decide whether to store it elsewhere.

Or course, you can slightly change this to make it a library rather than an interceptor by giving it a different name... This allows you to implement a fixed API for people to follow.

var storageLibrary = (function () {
    return {
        setItem: function (key, value) {
            alert(key);
            if (true) {
                localStorage.setItem(key, value);
            } else {
                // Save it somewhere else   
            }
        }
    };
}());

storageLibrary.setItem('a', 'b');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top