js查看localStorage和sessionStorage已使用内存

function get_cache_size(t){
    t = t == undefined ? "l" : t;
    var obj = "";
    if(t==='l'){
        if(!window.localStorage) {
            console.log('浏览器不支持localStorage');
        }else{
            obj = window.localStorage;
        }
    }else{
        if(!window.sessionStorage) {
            console.log('浏览器不支持sessionStorage');
        }else{
            obj = window.sessionStorage;
        }
    }
    if(obj!==""){
        var size = 0;
        for(let item in obj) {
            if(obj.hasOwnProperty(item)) {
                size += obj.getItem(item).length;
            }
        }
        console.log('当前已用存储:' + (size / 1024).toFixed(2) + 'KB');
    }
}
get_cache_size('l');//localStorage当前大小
get_cache_size('s');//sessionStorage当前大小
    原文作者:倾葵
    原文地址: https://blog.csdn.net/iocncc/article/details/114289659
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞