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');