web-dev-qa-db-ja.com

HTML5 localStorageの便利な関数// JavaScript、TypeScript

方法: *

  • localStorageがサポートされているかどうかを確認する
  • localStorageにアイテムがあるかどうかを確認する
  • localStorageに残っている容量を取得します
  • localStorageの最大容量を取得します
  • localStorageの使用済みスペースを取得します
  • localStorageのバックアップを取得
  • localStorageにバックアップを適用
  • localStorageのすべての情報をコンソールにダンプします

*以下の回答を確認してください


よくある質問:

  • [link]localStorageにオブジェクトを保存する方法
  • [link] 配列をlocalStorageに格納する方法
  • [link]localStorageに画像を保存する方法
  • [[リンク]localStorageチュートリアル(ストレージイベントおよびもカバー)覚えておくべきこと

関連:

  • [link] Webストレージに関する一般情報
  • [link]sessionStorage保存されたデータは、ページセッションが終了するとクリアされます
  • [link]indexedDB構造化データのクライアント側ストレージ用の低レベルAPI
17
CoderPi

JavaScriptとTypeScriptでのlocalStorageの関数群

  • isSupported
  • hasItem(key)
  • getSpaceLeft()
  • getMaximumSace()
  • getUsedSpace()
  • getItemUsedSpace()
  • getBackup()
  • applyBackup(backup, fClear, fOverwriteExisting)
  • consoleInfo(fShowMaximumSize)


GitHubGistのLocalStorage- Moduleとしての完全なコード: JavaScript および TypeScript
実際の例:on JSFiddle


localStorageがサポートされているかどうかを確認します- TypeScript-Version

_/**
  * Flag set true if the Browser supports localStorage, without affecting it
  */
var localStorage_isSupported = (function () {
    try {
        var itemBackup = localStorage.getItem("");
        localStorage.removeItem("");
        localStorage.setItem("", itemBackup);
        if (itemBackup === null)
            localStorage.removeItem("");
        else
            localStorage.setItem("", itemBackup);
        return true;
    }
    catch (e) {
        return false;
    }
})();
_


localStorageに項目があるかどうかを確認します- TypeScript-Version

_/**
 * Check if localStorage has an Item / exists with the give key
 * @param key the key of the Item
 */
function localStorage_hasItem(key) {
    return localStorage.getItem(key) !== null;
}
_


localStorageに残っている容量を取得します- TypeScript-Version

_/**
 * This will return the left space in localStorage without affecting it's content
 * Might be slow !!!
 */
function localStorage_getRemainingSpace() {
    var itemBackup = localStorage.getItem("");
    var increase = true;
    var data = "1";
    var totalData = "";
    var trytotalData = "";
    while (true) {
        try {
            trytotalData = totalData + data;
            localStorage.setItem("", trytotalData);
            totalData = trytotalData;
            if (increase)
                data += data;
        }
        catch (e) {
            if (data.length < 2) {
                break;
            }
            increase = false;
            data = data.substr(data.length / 2);
        }
    }
    if (itemBackup === null)
        localStorage.removeItem("");
    else
        localStorage.setItem("", itemBackup);
    return totalData.length;
}
_


localStorageの最大容量を取得- TypeScript-Version

_/**
 * This function returns the maximum size of localStorage without affecting it's content
 * Might be slow !!!
 */
function localStorage_getMaximumSize() {
    var backup = localStorage_getBackup();
    localStorage.clear()
    var max = localStorage_getRemainingSpace();
    localStorage_applyBackup(backup);
    return max;
}
_


localStorageの使用済みスペースを取得- TypeScript-Version

_/**
 * This will return the currently used size of localStorage
 */
function localStorage_getUsedSize() {
    var sum = 0;
    for (var i = 0; i < localStorage.length; ++i) {
        var key = localStorage.key(i)
        var value = localStorage.getItem(key);
        sum += key.length + value.length;
    }
    return sum;
}
_


アイテムの使用スペースを取得 TypeScript-Version

_/**
 * This will return the currently used size of a given Item,returns NaN if key is not found
 * @param key
 */
function getItemUsedSpace(key) {
    var value = localStorage.getItem(key);
    if (value === null) {
        return NaN;
    }
    else {
        return key.length + value.length;
    }
}
_


バックアップ連想配列のみ TypeScript-Version


localStorageのバックアップを取得- TypeScript-Version

_/**
 * This will return a localStorage-backup (Associative-Array key->value)
 */
function localStorage_getBackup() {
    var backup = {};
    for (var i = 0; i < localStorage.length; ++i) {
        var key = localStorage.key(i);
        var value = localStorage.getItem(key);
        backup[key] = value;
    }
    return backup;
}
_


バックアップをlocalStorageに適用する- TypeScript-Version

_/**
 * This will apply a localStorage-Backup (Associative-Array key->value)
 * @param backup            associative-array 
 * @param fClear             optional flag to clear all existing storage first.Default:true
 * @param fOverwriteExisting optional flag to replace existing keys. Default: true
 */
function localStorage_applyBackup(backup, fClear, fOverwriteExisting) {
    if (fClear === void 0) { fClear = true; }
    if (fOverwriteExisting === void 0) { fOverwriteExisting = true; }
    if (fClear == true) {
        localStorage.clear();
    }
    for (var key in backup) {
        if (fOverwriteExisting === false && backup[key] !== undefined) {
            continue;
        }
        var value = backup[key];
        localStorage.setItem(key, value);
    }
}
_


コンソールのlocalStorageのすべての情報をダンプします- TypeScript-Version

_/**
 * This functions dumps all keys and values of the local Storage to the console,
 * as well as the current size and number of items
 * @param fShowMaximumSize optional, flag show maximum size of localStorage. Default: false
 */
function localStorage_consoleInfo(fShowMaximumSize) {
    if (fShowMaximumSize === void 0) { fShowMaximumSize = false; }
    var amount = 0;
    var size = 0;
    for (var i = 0; i < localStorage.length; ++i) {
        var key = localStorage.key(i)
        var value = localStorage.getItem(key);
        console.log(amount, key, value);
        size += key.length + value.length;
        amount++;
    }
    console.log("Total entries:", amount);
    console.log("Total size:", size);
    if (fShowMaximumSize === true) {
        var maxSize = localStorage_getMaximumSize();
        console.log("Total size:", maxSize);
    }
}
_

ノート

  • 各キーと値は、文字列の長さに等しい正確な量のスペースを使用しています
  • 私のテストで許可されている最大ストレージ容量:〜5MB
    • 5000000エッジ
    • 5242880クローム
    • 5242880 Firefox
    • 5000000 IE
  • Firefoxの問題:for (var key in localStorage)を使用しないでください:for (var i = 0; i < localStorage.length; ++i) { var key = localStorage.key(i)localStorageメンバー関数をkeysとして与える_for..in_- loop

//例- http://jsfiddle.net/1rqtd7pg/1/

_console.log("LocalStorage supported:", LocalStorage.isSupported)
// true - I hope so anyways ????
if(LocalStorage.isSupported) {
    localStorage.setItem("asd", "ASDASD")                           
    // sets / overwrites the item "asd"
    localStorage.setItem("asd" + Math.random(), "ASDASD")           
    // set another item each time you refresh the page
    var backup = LocalStorage.getBackup()                           
    // creates a backup, we will need it later!
    console.log(JSON.stringify(backup))                             
    // this is how the backup looks like
    var usedSpace = LocalStorage.getUsedSpace()                     
    // amount of space used right now
    console.log("Used Space:", usedSpace)
    var maxSpace = LocalStorage.getMaximumSpace()                   
    // amount of maximum space aviable
    console.log("Maximum Space:", maxSpace)
    var remSpace = LocalStorage.getRemainingSpace()                 
    // amount of remaining space
    console.log("Remaining Space:", remSpace)
    console.log("SpaceCheck", maxSpace === usedSpace + remSpace)    
    // true
    console.log("hasItem", LocalStorage.hasItem("nothis0ne"))       
    // we don't have this one in our localStorage
    localStorage.clear()                                            
    // oops, we deleted the localStorage!
    console.log("has asd", LocalStorage.hasItem("asd"))              
    // item asd is lost ????
    LocalStorage.applyBackup(backup)                                
    // but we have a backup, restore it!
    LocalStorage.consoleInfo()                                      
    // show all the info we have, see the backup worked ????
}
_
21
CoderPi