覆盖localStorage的点表示法 [英] Override dot notation for localStorage

查看:189
本文介绍了覆盖localStorage的点表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图覆盖用于访问localStorage的点表示法。
我已设法覆盖getItem和setItem方法,如下所述:是否可以在HTML5中单独覆盖本地存储和会话存储?

I am trying to override the dot notation for access to localStorage. I already managed to override the getItem and setItem methods as described here: Is it possible to override Local Storage and Session Storage separately in HTML5?

现在我尝试创建一个代理也可以捕获点访问,但因为我似乎无法覆盖localStorage对象,如此处所示

Now I tried to create a Proxy to also catch the dot access, but since I seem to be unable to overwrite the localStorage object as tried here

localStorage  = new Proxy(localStorage, {
get: function(target, name) {
    if (!(name in target)) {
        console.log("Getting non-existent property '" + name + "'");
        return undefined;
    }
    return '123';
},
set: function(target, name, value) {
    if (!(name in target)) {
        console.log("Setting non-existent property '" + name + "', initial value: " + value);
    }
    target[name] = value;
}
});

现在,当我尝试它时,我仍然得到测试而不是123:

Now when I try it I still get test instead of 123:

localStorage.testKey = "test";
alert(localStorage.testKey)


推荐答案

< a href =https://html.spec.whatwg.org/multipage/webstorage.html#the-localstorage-attribute =nofollow noreferrertitle =HTML Standard - 11.2.3 localStorage属性> window.localStorage 是一个只读属性,所以你不能像那样重新分配它。

window.localStorage is a read-only property, so you cannot just reassign it like that.

(我建议开启严格模式,它会通过抛出异常提醒您注意这一事实。)

(I recommend turning on strict mode, which would have alerted you to this fact by throwing an exception.)

但是,它是可配置的。如果您首先从窗口对象中删除它,您的代码将按预期工作。

However, it is configurable. If you delete it from the window object first, your code will work as intended.

var lsProxy = new Proxy(localStorage, {
    /* insert descriptor here */
});

delete window.localStorage;
window.localStorage = lsProxy;

你也可以用 Object.defineProperty

Object.defineProperty(window, "localStorage", {
    value: lsProxy,
    configurable: true,
    enumerable: true,
    writable: false
}); 

这篇关于覆盖localStorage的点表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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