0
0

【JavaScript】Web Storageが使用可能か判定する方法

Last updated at Posted at 2024-02-09

以下のように判定用の関数を作成します。

function storageAvailable(type) {
  let storage
  try {
    storage = window[type]
    const x = "__storage_test__"
    storage.setItem(x, x)
    storage.removeItem(x)
    return true
  } catch (err) {
    return (
      err instanceof DOMException &&
      (err.name === "QuotaExceededError" ||
        err.name === "NS_ERROR_DOM_QUOTA_REACHED") &&
      storage &&
      storage.length !== 0
    )
  }
}

localStorageが使用可能か判定するには以下のようにします。

if (storageAvailable("localStorage")) {
  console.log("localStorageが使用可能です。")
} else {
  console.log("localStorageが使用できません。")
}

sessionStorageが使用可能か判定するには以下のようにします。

if (storageAvailable("sessionStorage")) {
  console.log("sessionStorageが使用可能です。")
} else {
  console.log("sessionStorageが使用できません。")
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0