localStorage,sessionStorage和cookie的好后备?

时间:2018-02-28 15:23:50

标签: javascript local-storage session-storage

我正在尝试找出当有人访问我们网站时存储数据的最佳后备方法。我们使用它来存储搜索过滤器首选项,特别是需要在站点移动时移动它们。理想情况下它适用于:

  • localStorage first
  • 回退到sessionStorage
  • 然后回退到cookies

我目前的设置看起来有点像:

var localStorageAvail = supports_html5_storage();
var storage = "local";
if (localStorageAvail == undefined || localStorageAvail == false || localStorageAvail == null) {
    storage = "cookie";
}

function supports_html5_storage() {
  var testKey = 'test', storage = window.localStorage;
  try {
    storage.setItem(testKey, '1');
    storage.removeItem(testKey);
    return true;
  } catch (error) {
    return false;
  }
}

function getValue(what) {
    if (storage == "cookie") {
        // get from cookie
        return readCookie(what);
    } else {
        // localstorage
        return localStorage.getItem(what)
    }
}

function setValue(what,value) {
    if (storage == "cookie") {
        // get from cookie
        writeCookie(what,value,365);
    } else {
        // localstorage
        localStorage.setItem(what,value)
    }
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


function writeCookie(name,value,days) {
   var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

FWIW ,我没有使用jQuery,我不想要包含额外的库来执行此操作。它需要全部在Vanilla JS中:)

我的问题:这样做的最佳方式是什么?我应该调整当前的方法,所以它还包括sessionStorage吗?或者有更好的方法来做到这一点?

0 个答案:

没有答案