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

[亡魂溺海] 提交于 2019-11-29 14:46:45

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!