程序员让前端飞

Safari无痕模式下,storage被禁用问题

2018-05-02  本文已影响0人  ITgecko

前言

解决方案

    try {
      sessionStorage.setItem('private_test', 1);
    } catch (e) {
      //无痕模式
    }

  // 隐私模式下面,把临时值存到window.name中去
  function NameStorage(type) {
    this.store = NameStorage[type];
  }


  Object.assign(NameStorage.prototype, {
    getItem: function(key) {
      return this.store[key];
    },
    setItem: function(key, value) {
      this.store[key] = value;
      this._saveNameValue();
    },
    removeItem: function(key) {
      delete this.store[key];
      this._saveNameValue();
    },
    clear: function() {
      this.store = {};
      this._saveNameValue();
    },
    _saveNameValue: function() {
      var ret = {
        session: NameStorage.session,
        local: NameStorage.local
      }

      window.name = JSON.stringify(ret);
    }
  });
  function keepName () {
    if (keepName.done) {
      return;
    }

    var ret;

    if (window.name) {
      try {
        ret = JSON.parse(window.name);
      } catch (e) {
        ret = {};
      }
    }

    if (!_.isPlainObject(ret)) {
      ret = {};
    }


    if (!ret.session) {
      ret.session = {};
    }

    if (!ret.local) {
      ret.local = {};
    }


    NameStorage.session = ret.session;
    NameStorage.local = ret.local;
    keepName.done = true;
  }

另外一些补充

上一篇 下一篇

猜你喜欢

热点阅读