hifiveの小さな便利機能、h5.apiの紹介「localStorage編」
hifiveには頻繁に使われるであろう機能をAPIとしてまとめており、h5.apiというネームスペースでアクセスできるようになっています。
今回はlocalStorageを便利にしてくれるh5.api.storageについて紹介します。
localStorageの利用可否を判定する
通常、WebブラウザがlocalStorageをサポートしているかどうかはwindow.localStorageという変数のあるなしで判定されます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (window.localStorage) { | |
// localStorageをサポート | |
} else { | |
// localStorageをサポートしていない | |
} |
しかしこの方法の場合、iOS/macOSのSafariにおけるプライベートブラウジングを使っている際に問題があります。この時には window.localStorage という変数は存在するものの、実際に書き込みを行うと QuotaExceededError が発生します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> localStorage.setItem("key", "val"); | |
QuotaExceededError (DOM Exception 22): The quota has been exceeded. |
そうした場合を踏まえて h5.api.storage.isSupported を使うと正しく localStorage の利用可否を判定できます。
ループ処理をサポートするeachメソッド
この他、ちょっと便利なeachメソッドが用意されています。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h5.api.storage.local.each((index, key, val) => { | |
// 順番に処理 | |
}); |
セッションストレージも使えます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h5.api.storage.session.each((index, key, val) => { | |
// 順番に処理 | |
}); |
オブジェクトの保存にも対応
保存時に serialize 、取得時に deserialize していますので文字列以外であっても扱えるようになっています。
幾つのキーがあるか判定できる getLength メソッド
これは localStorage.length を実行しているだけです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> h5.api.storage.local.getLength(); | |
5 | |
> h5.api.storage.session.getLength(); | |
3 |
機能自体は小粒ですが、頻繁に使われるであろう機能をまとめておくことで開発が効率的になります。ぜひお使いください。
コメントは受け付けていません。