2015-04-09 5 views
-3

Как получить количество свободной квоты в локальных хранилищах моих приложений?Как получить бесплатную локальную квоту хранилища?

Мне нужно получить оставшуюся сумму хранения в байтах, килобайтах, мегабайтах или в процентах. Также было бы неплохо получить визуальное представление о том, сколько свободной квоты у меня есть в локальном хранилище.

Спасибо!

Редактировать: Пожалуйста, обратите внимание, что это сообщение типа «ответит на ваш собеседник», и поэтому я не могу улучшить свое отношение. Сосредоточьтесь на ответе, потому что гостевая аудитория находится в названии, и в этом не так много.

ответ

2

enter image description here

Вот JSFiddle для моего крестик браузера (включая мобильные браузеры) решения. Обратите внимание, что вам может потребоваться разрешить «небезопасные» сценарии, чтобы это работало в jsfiddle, но оно не требует разрешения в вашем собственном использовании. Вы можете получить оставшуюся местную квоту хранилища, используя следующий код. Он также предупреждает вас, если локальное хранилище заполнено.

HTML

<h2>Remaining local storage quota</h2> 

<p id="quotaOutputText"></p> 
<p id="quotaOutputPercentText"></p> 

<div id="visualFreeQuota"><div id="visualQuotaFill"></div></div> 

<br/> 

<button id="getQuota">Get free quota visually</button><button id="fillQuota">Fill quota by 900 KB</button><button id="clearLocalStorage">Clear local storage</button> 

CSS

#visualFreeQuota{ 

    height: 20px; 
    width: 390px; 
    border: 1px solid black; 
    visibility: hidden; 

} 

#visualQuotaFill { 

    background-color: #000000; 
    height: 20px; 
    width: 0px; 

} 

JAVASCRIPT

$(document).ready(function() { 

//"Get free quota visually" button's functionality 
$("#getQuota").click(function() { 

    $("#visualFreeQuota").css("visibility","visible"); 
    $("#getQuota").prop("disabled", true); //disables the button in order to prevent browser slowing down because of button spam (cannot spam 900 KB of data in local storage with good performance) 

}); 

//"Fill quota by 900 KB" button's functionality 
$("#fillQuota").click(function() { 

    $("#fillQuota").prop("disabled", true); 
    var fillData = ""; 

    if(localStorage.getItem("filledQuota")) { 

     fillData = localStorage.getItem("filledQuota"); 

    } 

    //Fills local storage by 900 KB 
    for(var i = 0; i < 1000001; i++) { 

     fillData += "add9bytes"; //adds 9 bytes of data in the variable 

     if(i === 100000) { 

      try { 

       localStorage.setItem("filledQuota", fillData); //saves data to local storage only once in this loop for increased performance 

      }catch(e) { 

       //Alerts the user if local storage does not have enough free space 
       alert("Local storage does not have free 900 KB!"); 

      }; 

     } 

    } 

    setOutputQuota(); 

    setTimeout(function() { 

     $("#fillQuota").prop("disabled", false); 

    }, 500); 

}); //"Fill quota by 900 KB" button's functionality end 

//"Clear local storage" button's functionality 
$("#clearLocalStorage").click(function() { 

    localStorage.clear(); 
    setOutputQuota(); 

}); 

//Sets free local storage quota on document.ready when no buttons are yet pressed 
setOutputQuota(); 

}); 

//returns the amount of remaining free bytes in local storage quota 
function getRemainingQuotaInBytes() { 

    return 1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length; 

} 

//returns the % of free local storage quota 
function getRemainingQuotaInPercent() { 

    return Math.round((1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length)/(1024 * 1024 * 5) * 100); 

} 

//sets quota texts 
function setOutputQuota() { 

    $("#visualQuotaFill").css("width", parseInt($("#visualFreeQuota").css("width"))/100 * (100 - getRemainingQuotaInPercent()) + "px"); 
    $("#quotaOutputText").text(Math.round(getRemainingQuotaInBytes()/1000) + " KB free in your local storage"); 
    $("#quotaOutputPercentText").text(getRemainingQuotaInPercent() + " % of the quota free in your local storage"); 

} 

 Смежные вопросы

  • Нет связанных вопросов^_^