1. 程式人生 > >localStorage儲存資料,若是IE11以下使用cookie儲存

localStorage儲存資料,若是IE11以下使用cookie儲存

IE11以下不支援localStorage,若瀏覽器不支援,使用cookie儲存

var util = {
  // 獲取 localStorage
  getItem: function (item) {
    var value;
    if (this.hasLocalSotrage()) {
      try {
        value = localStorage.getItem(item);
      } catch (error) {
        console.error('localStorage.getItem報錯, ', error.message)
      } finally
{ return value; } } else { return this.getCookie(item); } }, // 設定 localStorage setItem: function (key, value, day) { if (this.hasLocalSotrage()) { try { // safari 無痕模式下,直接使用localStorag.setItem 會報錯 localStorage.setItem(key, value); } catch
(error) { console.error('localStorage.setItem報錯, ', error.message) } } else { this.setCookie(key, value, day); } }, // 判斷瀏覽器是否支援 hasLocalSotrage hasLocalSotrage: function () { return window.Storage && window.localStorage && window.localStorage instanceof
Storage }, //設定cookie setCookie: function (key, value, day) { var t = day || 30; var d = new Date(); d.setTime(d.getTime() + (t * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toUTCString(); document.cookie = key + "=" + value + "; " + expires; }, //獲取cookie getCookie: function (name) { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) { return arr[2]; } else { return null; } } }