Is it possible to override the local storage and session storage separately in HTML5?

I know that you can override the HTML5 storage APIs by overriding Storage.prototype.getItem, setItem, removeItem and clean. But this will replace these methods for both local storage and session storage.

Is it possible to simply override one and not the other? Or redefine both separately?

A little context: I have an existing application that uses both local storage and session storage very heavily. I want to add a temporary code to reflect the material in the local store in another store, but I do not want to drag the contents of the session store with it.

I can update every link to localStorage to call some wrapper function that could do the mirroring, but I really don't want to update all these calls. It would be easier if I could localize this code by overriding one set of storage methods.

+4
source share
1 answer

There are several possibilities to achieve what you want. But remember that none of them should be used in a production environment.

The first parameter determines whether the setItem method was called by the sessionStorage or localStorage . You can write like this:

 var _setItem = Storage.prototype.setItem; Storage.prototype.setItem = function(key, value) { if (this === window.localStorage) { // do what you want if setItem is called on localStorage } else { // fallback to default action _setItem.apply(this, arguments); } } 

Second, replaces the prototype of the sessionStorage or localStorage . It might look like this:

 localStorage.__proto__ = Object.create(Storage.prototype); localStorage.__proto__.setItem = function() { // your logic here } 

Please note that I used the __proto__ pseudo property, which is non-standard, but available in Chrome and Firefox. (I don’t know about Opera, Safari and others). However, as you can see, this can be useful during development.

+9
source

All Articles