萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 本地存儲方案:LocalStorage 與 UserData 結合完美替代 Cookie

背景:為什麼要替換 Cookie?

存儲方案支援瀏覽器容量備註
Cookie全部4 KB每次請求自動攜帶,浪費帶寬
UserData僅 IE64 KB/文檔,640 KB/域IE 專屬行為
Flash SharedObject需 Flash 插件100 KB非原生,移動端不支援
Google Gears SQLite需 Gears 插件無限制已停止維護
LocalStorageIE8+、FF3.5+、Chrome4+、Safari4+、Opera10.5+、iOS2+、Android2+5 MB/域HTML5 標準,原生支援

結論:採用 LocalStorage(現代瀏覽器)+ UserData(IE7-) 雙模式策略,全面替代 Cookie。

核心難點與解決方案

1. 過期時間模擬

LocalStorage 無原生過期 API。方案:存儲時附帶 expires 時間戳,讀取時校驗,過期則刪除並返回 null。

2. 批量操作 API 封裝

原生 API 僅支援單鍵值操作,封裝 setAll()、getAll()、removeAll()、clear() 提升開發效率。

完整實現代碼(核心邏輯)

IE UserData 存儲引擎

// 創建隱藏 input 元素掛載 UserData 行為
function _getInstance() {
  const input = document.createElement('input');
  input.type = 'hidden';
  input.addBehavior('#default#userData');
  document.body.appendChild(input);
  return input; // 每次創建新實例避免磁盤配額衝突
}

// 存儲
function __setItem(key, config) {
  try {
    const input = _getInstance();
    if (config.expires) {
      const expires = (typeof config.expires === 'number')
        ? new Date(Date.now() + config.expires)
        : config.expires;
      input.expires = expires.toUTCString();
    }
    input.setAttribute(config.key, config.value);
    input.save(config.key); // 文件名:key[1].xml
  } catch (e) { /* 靜默失敗 */ }
}

// 讀取
function _getItem(config) {
  try {
    const input = _getInstance();
    input.load(config.key);
    return input.getAttribute(config.key) || null;
  } catch (e) { return null; }
}

// 刪除(設置過期時間為過去)
function _removeItem(config) {
  try {
    const input = _getInstance();
    input.load(config.key);
    input.removeAttribute(config.key);
    const expires = new Date(Date.now() - 1);
    input.expires = expires.toUTCString();
    input.save(config.key);
  } catch (e) { /* ignore */ }
}

LocalStorage 存儲引擎(現代瀏覽器)

const LS = window.localStorage;

function _lsSetItem(key, config) {
  try {
    const payload = {
      value: config.value,
      expires: config.expires ? (typeof config.expires === 'number'
        ? Date.now() + config.expires
        : config.expires.getTime()) : null
    };
    LS.setItem(key, JSON.stringify(payload));
  } catch (e) { /* 配額滿等 */ }
}

function _lsGetItem(key) {
  try {
    const raw = LS.getItem(key);
    if (!raw) return null;
    const { value, expires } = JSON.parse(raw);
    if (expires && Date.now() > expires) {
      LS.removeItem(key);
      return null;
    }
    return value;
  } catch (e) { return null; }
}

function _lsRemoveItem(key) { LS.removeItem(key); }

統一門面模式(qext.LocalStorage)

const qext = qext || {};
qext.LocalStorage = (function() {
  const isIE = /*@cc_on!@*/false || !!document.documentMode; // 簡易 IE 檢測
  const engine = (isIE && document.documentMode < 8) ? 'userData' : 'localStorage';

  return {
    set: function(key, value, expires) {
      const config = { key, value, expires };
      engine === 'userData' ? __setItem(key, config) : _lsSetItem(key, config);
    },
    get: function(key) {
      return engine === 'userData' ? _getItem({ key }) : _lsGetItem(key);
    },
    remove: function(key) {
      engine === 'userData' ? _removeItem({ key }) : _lsRemoveItem(key);
    },
    // 批量操作...
  };
})();

使用示例

// 存儲用戶偏好,30天過期
qext.LocalStorage.set('theme', 'dark', 30 * 24 * 60 * 60 * 1000);

// 讀取
const theme = qext.LocalStorage.get('theme'); // 'dark' 或 null

// 刪除
qext.LocalStorage.remove('theme');

優勢總結

  • ✅ 容量從 4KB → 5MB(現代瀏覽器)/ 64KB(IE7-);
  • ✅ 不隨 HTTP 請求發送,節省帶寬;
  • ✅ 用戶手動清理 Cookie 通常不會清理 LocalStorage/UserData,數據更持久;
  • ✅ 統一 API 屏蔽瀏覽器差異,業務代碼零感知遷移。

這套方案在 2015 年項目中穩定運行,支撐百萬級用戶端本地緩存需求。現代項目建議優先使用 localForage 或 Dexie.js(IndexedDB 封裝),獲得更大容量、異步非阻塞、索引查詢等進階能力。

copyright © 萬盛學電腦網 all rights reserved