SafariのプライベートブラウジングでWebStorageが使用できない挙動と対処法


iOSとMacのSafariでプライベートブラウジング中にlocalStoragesessionStorageを使うとエラーになってしまいます。(Windowsは確認してない)

プライベートブラウジング中
sessionStorage.setItem("test", "test");
// Error: QuotaExceededError: DOM Exception 22

そしてwindow.sessionStorageundefinedとならないためif文での分岐はできません。

プライベートブラウジング中
!!(window.sessionStorage);
// true

しかしエラーが発生するのはsetItemのときのみで、それぞれgetItemではエラーになりません。データをセットできないので返り値はnullです。

プライベートブラウジング中
sessionStorage.getItem("test");
// null

対処法

sessionStorage.setItemを直接使用せずにデータセット用の関数を作ってしまう。

function setSessionStorage(key, value) {
  if (!window.sessionStorage) return;
  try {
    sessionStorage.setItem(key, value);
  } catch (err) {
    console.error(err);
  }
}

function setLocalStorage(key, value) {
  if (!window.localStorage) return;
  try {
    localStorage.setItem(key, value);
  } catch (err) {
    console.error(err);
  }
}

こんな感じでtry-catchで囲んでエラーで処理が止まらないようにしました。
WebStorageを使うときは必ずsetSessionStorage()setLocalStorage()から呼び出します。

ちなみに

ChromeのシークレットモードやFirefoxのプライベートブラウジングでは通常モードとはStorageが切り離されますがWebStorageは普通に使えます。
Safari・・・