【问题标题】:How to deal with sessionStorage locally in FF (for testing)如何在FF本地处理sessionStorage(测试用)
【发布时间】:2012-02-24 09:19:50
【问题描述】:

我正在尝试为我的所有 JS 编写测试,并且测试(我正在使用 Jasmine)在浏览器中本地运行。由于安全限制 (?) sessionStorage 在 Firefox 中本地无法工作(在浏览器中查看 file:///...)。

快速示例:

window.sessionStorage.setItem('foo', 'bar');

这给出“错误:不支持操作”。

我尝试用自己的模拟方法覆盖 window.sessionStorage,但没有成功。

我目前唯一的解决方案是将与 sessionStorage 相关的所有内容放在 try/catch 块中。

对于如何最好地处理这个问题有什么建议吗?

【问题讨论】:

    标签: javascript jasmine sessionstorage


    【解决方案1】:

    Object.defineProperty 似乎可以使用它,您可以模拟 sessionStorage 使用它:

    var mockup = function() {
      var table = {};
      return {
        getItem: function(key) {
          return table[key];
        },
        setItem: function(key, value) {
          table[key] = value.toString();
        },
        clear: function() {
          table = {};
        }
      };
    }();
    Object.defineProperty(window, 'sessionStorage', { value: mockup });
    // should output "Object { getItem=function(), setItem=function(), clear=function()}"
    console.log(window.sessionStorage);
    

    但此模型不适用于 sessionStorage (window.sessionStorage[key] = value) Proxyindexer 构建 mockup 对象。

    【讨论】:

    • 当值不存在时,getItem 应该返回 NULL。所以应该是return items[key] ? items[key] : null
    【解决方案2】:

    如果你使用:http://nbubna.github.io/store/,你会自动获得本地模拟

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2013-11-10
      相关资源
      最近更新 更多