HTML5 localStorage 有用的函数 // JavaScript,TypeScript [关闭]

Posted

技术标签:

【中文标题】HTML5 localStorage 有用的函数 // JavaScript,TypeScript [关闭]【英文标题】:HTML5 localStorage useful Functions // JavaScript, TypeScript [closed] 【发布时间】:2016-03-18 16:02:12 【问题描述】:

如何:*

检查是否支持localStorage 检查localStorage是否有物品 获取localStorage中剩余的空间量 获取localStorage中的最大空间量 获取localStorage中的已用空间 获取localStorage 的备份 将备份应用到localStorage 在控制台中转储localStorage的所有信息

*检查下面的答案


常见问题:

[link]localStorage中如何存储对象 [link]如何在localStorage中存储一个数组 [link]如何将图片保存到localStorage [link] localStorage 教程(还包括存储事件要记住的事情

相关:

[link] Web 存储的一般信息 当页面会话结束时,[link]sessionStorage 存储的数据会被清除 [link] indexedDB 用于客户端存储结构化数据的低级 API

【问题讨论】:

嘿,虽然我们通常宽恕甚至鼓励写长而详细的问答,但这篇文章更像是一个标签维基。它没有以问题和答案的形式进行格式化,也没有解决或详细说明任何特定问题。 如你所见,我投入了相当多的时间,回答了这 8 个问题。虽然它们可以作为单独的问答发布,但我觉得它们可以在一个干净的主题中一起回答,在以后的问题、搜索和一般帮助中用作参考。如果愿意,我可以将其发布为 5 个问题。但是,如果这太开箱即用,我会保证不再用我的答案滥用 ***。 @CodeiSir 非常感谢您在此处提供的代码。谢谢。 【参考方案1】:

我在 javascript 和 TypeScript 中的 localStorage 函数套件

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

完整代码为 GitHubGist 上的 LocalStorage-Module:JavaScript 和 TypeScript 现场示例: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 是否有 Item - 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 火狐 5000000 IE Firefox 问题: 不要使用for (var key in localStorage),但是: for (var i = 0; i &lt; localStorage.length; ++i) var key = localStorage.key(i)for..in-loop 会将 localStorage 成员函数作为 keys

// 示例 - 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 ?

【讨论】:

这是一个 npm 包吗?如果没有,你能制作一个然后在 dev.to 上写一篇关于它的帖子吗?我想你会得到很多贡献者。 @Tamb 我创建了我的第一个 npm 包,如果有任何反馈请告诉我npmjs.com/package/localstorage-ext :)

以上是关于HTML5 localStorage 有用的函数 // JavaScript,TypeScript [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

html5 localstorage能存多少

html5 localStorage(本地存储)

[html5]localStorage的原理和HTML5本地存储安全性

html5 localstorage 怎么取存储条数

html5的localstorage详解

android html5 localstorage某手机从localstorage中取不到数据