Skip to main content




Persistent storage can help protect critical data from eviction and reduce the chance of data loss.


Updated

Cuando se enfrentan a presiones de almacenamiento como poco espacio en disco, los browsers normalmente desalojarán los datos, incluso de la API from cache e IndexedDB, del origen menos utilizado recientemente. Esto puede provocar la pérdida de datos si la aplicación no ha sincronizado los datos con el server y reducir la confiabilidad de la aplicación al eliminar los recursos necesarios para que funcione, lo que genera experiencias negativas para el Username.

Afortunadamente, la investigación del equipo de Chrome muestra que Chrome rara vez borra los datos automáticamente. Es mucho más común que los usuarios borren manualmente el almacenamiento. Por lo tanto, si un usuario visita su sitio con regularidad, hay pocas posibilidades de que sus datos sean desalojados. Para evitar que el browser elimine sus datos, puede solicitar que todo el almacenamiento de su sitio se marque como persistente.

Requesting that all data on your site be marked as persistent should only be done for critical data (e.g. end-to-end encryption keys) which, if not backed up to the cloud, could result in significant data loss if not are saved. The browser does not delete the persistent storage, even if the storage is running low. It will only be removed if the user chooses to remove it through their site settings.

Persistent storage is supported by many modern navegadores. Para obtener más información sobre el desalojo, cuánto puede almacenar y cómo manejar las limitaciones de las cuotas, consulte Almacenamiento para la Web.

Check if your site storage has been marked as persistent

Puede utilizar JavaScript para determinar si el almacenamiento de su sitio se ha marcado como persistente. Vocación navigator.storage.persisted () returns a Promise that resolves to a Boolean, indicating whether the storage has been marked as persistent.


if (navigator.storage && navigator.storage.persist) {
const isPersisted = await navigator.storage.persisted();
console.log(`Persisted storage granted: ${isPersisted}`);
}

When should I request persistent storage?

The best time to request that your storage be marked as persistent is when you save critical user data, and the request should ideally be wrapped in a user gesture. Do not ask for persistent storage on page load, or other startup code, the browser may ask the user for permission. If the user is not doing anything that they think should be saved, the message can be confusing and they will probably reject the request. Also, don't warn too often. If the user decided not to grant permission, do not ask again immediately on the next save.

Request persistent storage

To request persistent storage for your site data, call
navigator.storage.persist (). Returns a Promise that resolves to a Boolean, indicating whether persistent storage permission was granted.


if (navigator.storage && navigator.storage.persist) {
const isPersisted = await navigator.storage.persist();
console.log(`Persisted storage granted: ${isPersisted}`);
}

API names for check if your site storage has already been marked as persistent, and request persistent storage is very similar. The way I remember the difference is persisted () is past tense and is used to check if it already persistsed. While persist () it is in the present tense and asks for it now.

How is permission granted?

Persistent storage is treated as Excuse me. Browsers use different factors to decide whether to grant persistent storage permissions.

Chrome and other Chromium-based browsers

Chrome and most other Chromium-based browsers automatically handle the permission request and do not display any messages to the user. Instead, if a site is deemed important, persistent storage permission is automatically granted; otherwise, it is silently denied.

Heuristics for determining whether a site is important include:

  • What level of participation does the site have?
  • Has the site been installed or bookmarked?
  • Has the site been granted permission to display notifications?

If the request was denied, it can be requested again later and will be evaluated using the same heuristic.

Firefox

Firefox delegates the permission request to the user. When persistent storage is requested, the user is prompted for a UI popup asking if they will allow the site to store data in persistent storage.

ff-persist-request-4761055

A pop-up window that displays Firefox when a site requests persistent storage.

What storage is protected by persistent storage?

If persistent storage permission is granted, the browser will not evict data stored in:

  • Cache API
  • Cookies
  • DOM storage
  • Filesystem API (file system provided by browser and sandboxed)
  • IndexedDB
  • Service workers
  • Application cache (deprecated, should not be used)
  • WebSQL (deprecated, should not be used)

How to disable persistent storage

At this time, there is no programmatic way to tell the browser that it no longer needs persistent storage.

conclusion

La investigación del equipo de Chrome muestra que, aunque es posible, Chrome rara vez borra automáticamente los datos almacenados. Para proteger los datos críticos que pueden no almacenarse en la nube, o que resultarán en una pérdida significativa de datos, el almacenamiento persistente puede ser una herramienta útil para garantizar que el navegador no elimine sus datos cuando el dispositivo local se enfrenta a la presión del almacenamiento. Y recuerde, solicite almacenamiento persistente solo cuando be más probable que el usuario lo desee.

Thanks

A special thanks to Victor Costan and Joe Medley for reviewing this article. Thanks to Chris Wilson, who wrote the original version of this article that first appeared on WebFundamentals.

Heroic image of Umberto in Unsplash