获取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(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当前大小
posted @ 2019-12-25 14:04  expworld  阅读(1706)  评论(0编辑  收藏  举报