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

后端 未结 2 423
遥遥无期
遥遥无期 2020-12-19 06:37

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 bot

相关标签:
2条回答
  • 2020-12-19 07:20

    Yes, Local Storage and Session Storage override separately in HTML5

    localStorage.setItem('name', Krishna); //here local storege value is Krishna
    sessionStorage.name = "Krishna"; //here Session storege value is Krishna
    

    In below we override Local Storage and Session Storage value separately

    localStorage.setItem('name', Sri); //here local storege value is Sri
    sessionStorage.name = "Pal"; //here Session storege value is Pal
    
    0 讨论(0)
  • 2020-12-19 07:31

    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.

    0 讨论(0)
提交回复
热议问题