SafariのプライベートブラウジングでWebStorageが使用できない挙動と対処法
4522 ワード
iOSとMacのSafariでプライベートブラウジング中にlocalStorageとsessionStorageを使うとエラーになってしまいます。(Windowsは確認してない)
プライベートブラウジング中
sessionStorage.setItem("test", "test");
// Error: QuotaExceededError: DOM Exception 22
そしてwindow.sessionStorageがundefinedとならないため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・・・
Author And Source
この問題について(SafariのプライベートブラウジングでWebStorageが使用できない挙動と対処法), 我々は、より多くの情報をここで見つけました https://qiita.com/narikei/items/f55fb9cb398beac52ea9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .