是否可以在HTML5中单独覆盖本地存储和会话存储? [英] Is it possible to override Local Storage and Session Storage separately in HTML5?

查看:82
本文介绍了是否可以在HTML5中单独覆盖本地存储和会话存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以通过覆盖Storage.prototype.getItem,setItem,removeItem和clear来覆盖HTML5存储API。但是,这将覆盖本地存储会话存储的那些方法。

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.

我可以更新对localStorage的每个引用来调用一些可以执行镜像的包装器函数,但我真的不想更新所有这些调用。如果我可以通过覆盖一组存储方法来本地化这些代码,那将更加清晰。

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.

推荐答案

有几种可能性实现你想要的。但请记住,它们都不应该在生产环境中使用。

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

第一个选项检测是否调用 setItem 方法通过 sessionStorage localStorage 对象。你可以这样写:

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

第二个,替换<$ c $的原型c> sessionStorage 或 localStorage 对象。它可能如下所示:

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
}

注意,我使用了 __ proto __ 伪属性,这是非标准的,但在Chrome和Firefox中公开。 (不了解Opera,Safari等)。但是,您可以看到它在开发过程中可能会有所帮助。

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.

这篇关于是否可以在HTML5中单独覆盖本地存储和会话存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆