摘要localStorage

时间:2018-01-09 23:10:38

标签: javascript html5 local-storage session-storage

我一直在构建一个Angular2库,它为localStorage和sessionStorage添加了一层抽象,以添加权限级别和好处以及诸如此类的功能。我遇到的问题是,如果其他开发人员尝试直接访问localStorage或sessionStorage,我想抛出错误。确保正确使用权限和其他内容。

所以要做到这一点基本上我想复制localStorage和sessionStorage引用,然后覆盖它们的函数如下:

  this.localStorageReference = Object.assign({}, localStorage);
  this.sessionStorageReference = Object.assign({}, sessionStorage);

  const err = "Use the StorageStrategy, not localStorage or sessionStorage.";
  Storage.prototype._setItem = Storage.prototype.setItem;
  Storage.prototype.setItem = function(key, value)
  {
    throw Error(err);
  }

  Storage.prototype._getItem = Storage.prototype.getItem;
  Storage.prototype.getItem = function(key){
    throw Error(err);
  }

哪些覆盖效果很好并抛出错误,问题是Object.assign似乎并没有复制我需要的东西。因为当我尝试使用引用时,我没有任何方法。

this.localStorageReference.setItem(key, obj);

结果:

TypeError: this.localStorageReference.setItem is not a function

查看localStorage文档,我没有看到任何明显的内容。任何想法?

1 个答案:

答案 0 :(得分:2)

看看Object.keys(localStorage)。 您会注意到您没有看到任何方法名称。同样处理for (let key in localStorage)或其他任何你想要尝试的事情。

这些函数不是可枚举的,或者是原型而不是实例。无论哪种方式,它们都不会出现在"拥有"的枚举查找中。密钥。

const fakeStorage = ["clear", "setItem", "getItem", "removeItem", /*...*/]
  .map(method => [method, localStorage[method].bind(localStorage)])
  .reduce((obj, [key, value]) => {
    obj[key] = value;
    return obj;
  }, {});

现在我不是通过键枚举,而是枚举已知的方法名称。 另请注意,Storage的某些实现构建为防篡改(只读属性;如果方法不在正确的对象上则抛出错误;等等)。

这引出了一个问题......为什么不保护自己的访问权限,而不是强制要求破坏其他人的使用?

相关问题