Introduction to the
Generally, Web applications store data locally in a variety of ways. Such as indexedDb, Cache Api, or localStorage. All of this storage, of course, takes up storage space on the local machine.
When the local storage space is insufficient, the browser automatically clears the local storage space to obtain more available storage space. For offline applications or PWA, this is unfortunate. Maybe the local data has not been synchronized to the server, or the application itself wants to provide offline access. The good news is that browsers give us two storage modes:
- Best effort: Temporary storage
- Persistent: Persistent storage
The default mode, of course, is “Best effort”, which is automatically cleaned up by the browser when it runs out of storage space. But in persistent mode, the browser doesn’t remove it automatically, you have to remove it manually.
How to apply for “Persistent” storage mode
We can apply through the following code.
/** * Request persistent storage. */
function grantPersist() {
return wrapPromise((resolve, reject) = > {
if (navigator.storage && navigator.storage.persist) {
navigator.storage.persist().then(granted= > {
// granted: true / false
if(granted){
console.log("Persistent storage mode, need to be manually cleared.")}else{
console.log("Temporary storage mode, when the storage space is insufficient, the browser will automatically clear.")
}
resolve(granted);
});
} else {
reject('the navigator. Storage. Persist: does not support'); }}); }Copy the code
Is user authorization required?
- After Chrome 55, the browser will automatically authorize a site if it meets any of the following criteria. No user confirmation is required.
- The site has been bookmarked and the user has no more than five bookmarks
- The site has a high “site engagement”. This can be viewed with this command: chrome://site-engagement/
- The site has been added to the home screen
- Push notification is enabled on the site.
Anything other than the above will be automatically rejected.
- On Firefox: there will be a popup box that requires user authorization.
If you look at the current storage mode
We can call the navigator. Storage. “persist” the API to look at it
/** * Check the storage mode */
function checkPersisted() {
return wrapPromise((resolve, reject) = > {
if (navigator.storage && navigator.storage.persisted) {
navigator.storage.persisted().then(persisted= > {
if(persisted){
console.log('The current mode is persistent and the data stored locally needs to be cleaned manually by the user')
}esle{
console.log('The current mode is temporary and the browser will automatically erase local data when running out of space')
}
resolve(persisted)
});
} else {
reject('the navigator. Storage. Persisted does not support'); }}); }Copy the code
Can YOU view the available storage space and the used space?
We can look at it through the API
/** * gets information about available disk space and used space. */
function estimateSpace() {
return new Promise((resolve, reject) = > {
if (navigator.storage && navigator.storage.estimate) {
navigator.storage.estimate().then(estimate= > {
// The original unit is byte. Convert to MB
const ut = 1024 * 1024;
resolve({
total: estimate.quota / ut,
usage: estimate.usage / ut
});
});
} else {
reject('the navigator. Storage. Estimate: does not support'); }}); }Copy the code
Browser Compatibility
Browser compatibility
Demo, complete code
- util.js
function wrapPromise(cb) {
return new Promise((resolve, reject) = > cb(resolve, reject));
}
/** * User authorization. Request persistent storage. */
function grantPersist() {
return wrapPromise((resolve, reject) = > {
if (navigator.storage && navigator.storage.persist) {
navigator.storage.persist().then(granted= > {
// granted: true/false
resolve(granted);
});
} else {
reject('navigator.storage.persist: the browser is not supported'); }}); }/** * Check the storage mode */
function checkPersisted() {
return wrapPromise((resolve, reject) = > {
if (navigator.storage && navigator.storage.persisted) {
navigator.storage.persisted().then(result= > resolve(result));
} else {
reject('navigator.storage.persisted is not support'); }}); }/** * gets information about available disk space and used space. */
function estimateSpace() {
return new Promise((resolve, reject) = > {
if (navigator.storage && navigator.storage.estimate) {
navigator.storage.estimate().then(estimate= > {
// The original unit is byte. Convert to MB
const ut = 1024 * 1024;
resolve({
total: estimate.quota / ut,
usage: estimate.usage / ut
});
});
} else {
reject('navigator.storage.estimate: the browser is not supported'); }}); }Copy the code
- index.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="./util.js"></script>
</head>
<body>
<button id="btn">The user authorization</button>
<h1>Browser stores information</h1>
<h1 id="diskInfo"></h1>
<hr />
<h1>The current storage mode is:</h1>
<h1 id="persistInfo"></h1>
<script>
// Check the browser's storage mode.
function getPersisted(a) {
checkPersisted().then(
persisted => {
document.querySelector('#persistInfo').innerHTML = persisted
? 'persistent'
: 'temporary';
},
error => {
document.querySelector('#persistInfo').innerHTML = error; }); }// Apply for the persistent storage permission.
function applyPersist(a) {
grantPersist().then(
result => {
getPersisted();
},
error => {
document.querySelector('#persistInfo').innerHTML = error; }); }// Get information about available disk space and used space
function checkStorageSpace(a) {
estimateSpace().then(
data => {
const { total, usage } = data;
document.querySelector('#diskInfo').innerhtml = 'Total size: ${(total /1024
).toFixed(4)}GB, ${(usage /1024).toFixed(4)}GB`;
},
error => {
document.querySelector('#diskInfo').innerHTML = error; }); }function init(a) {
checkStorageSpace();
getPersisted();
document.querySelector('#btn').onclick = function(a) {
applyPersist();
};
}
window.onload = init;
</script>
</body>
</html>
Copy the code
- Screenshot after application