30秒学会 JavaScript 片段 · 2023年3月26日

30秒学会 JavaScript 片段 – Check if sessionStorage is enabled

Checks if sessionStorage is enabled.

  • Use a try...catch block to return true if all operations complete successfully, false otherwise.
  • Use Storage.setItem() and Storage.removeItem() to test storing and deleting a value in Window.sessionStorage.

代码实现

const isSessionStorageEnabled = () => {
  try {
    const key = `__storage__test`;
    window.sessionStorage.setItem(key, null);
    window.sessionStorage.removeItem(key);
    return true;
  } catch (e) {
    return false;
  }
};

isSessionStorageEnabled(); // true, if sessionStorage is accessible

翻译自:https://www.30secondsofcode.org/js/s/is-session-storage-enabled