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当前大小

你可能感兴趣的:(笔记)