Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to override Local Storage and Session Storage separately in HTML5?

I know it's possible to override the HTML5 storage APIs by overriding Storage.prototype.getItem, setItem, removeItem and clear. But that will override those methods for both local storage and session storage.

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

A little context: I have an existing app that makes very heavy use of both local storage and session storage. I want to add some temporary code to mirror the stuff in local storage in another storage mechanism, but I don't want to drag the session storage contents along with it.

I could update every reference to localStorage to call some wrapper function that could do the mirroring, but I really don't want to update all those calls. It would be way cleaner if I could localize this code by overriding a single set of storage methods.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

The first option detects if setItem method was called by sessionStorage or localStorage object. You could write it this way:

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

The second one, replaces prototype of sessionStorage or localStorage object. It may look like this:

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

Notice, that I used __proto__ pseudo property which is non-standard, but exposed in Chrome and Firefox. (Don't know about Opera, Safari and others). However, as you can see it might be helpful during development.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...