以下のように判定用の関数を作成します。
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が使用できません。")
}