You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Web storage objects`localStorage`and `sessionStorage`allow to save key/value pairs in the browser.
Los objetos de almacenaje web`localStorage`y `sessionStorage`permiten guardar pares de clave/valor en el navegador.
What's interesting about them is that the data survives a page refresh (for`sessionStorage`)and even a full browser restart (for`localStorage`).We'll see that very soon.
Lo que es interesante sobre ellos es que los datos sobreviven a una recarga de página (en el caso de`sessionStorage`)y hasta un reinicio completo de navegador (en el caso de`localStorage`).Lo veremos en breve.
We already havecookies.Why additional objects?
Ya tenemoscookies.¿Por qué tener objetos adicionales?
-Unlikecookies,web storage objects are not sent to server with each request. Because of that, we can store much more. Most browsers allow at least2 megabytesof data (or more) and have settings to configure that.
-The server can't manipulate storage objectsviaHTTP headers, everything's done in JavaScript.
-The storage is bound to the origin (domain/protocol/port triplet).That is, different protocols or subdomains infer different storage objects, they can't access data from each other.
-Al contrario que lascookies,los objetos de almacenaje web no se envian al servidor en cada petición. Debido a esto, podemos almacenar mucha más información. La mayoría de navegadores permiten almacenar, como mínimo,2 megabytesde datos (o más) y tienen opciones para configurar éstos límites.
-El servidor no puede manipular los objetos de almacenajeviacabezeras HTTP, todo se hace via JavaScript.
-El almacenaje está vinculado al orígen (al triplete dominio/protocolo/puerto).Esto significa que distintos protocolos o subdominios tienen distintos objetos de almacenaje, no pueden acceder a otros datos que no sean los suyos.
Both storage objects provide same methods and properties:
Ámbos objetos de almacenaje proveen los mismos métodos y propiedades:
- `setItem(key, value)` --store key/value pair.
- `getItem(key)` --get the value by key.
- `removeItem(key)` --remove the key with its value.
- `clear()` --delete everything.
- `key(index)` --get the key on a given position.
- `length` --the number of stored items.
- `setItem(clave, valor)` --almacenar un par clave/valor.
- `getItem(clave)` --obtener el valor por medio de la clave.
- `removeItem(clave)` --eliminar la clave y su valor.
- `clear()` --borrar todo.
- `key(índice)` --obtener la clave de una posición dada.
- `length` --el número de ítems almacenados.
Let's see how it works.
Vamos a ver cómo funciona.
##localStorage demo
##Demo de localStorage
The main features of `localStorage`are:
Las principales funcionalidades de `localStorage`son:
- Shared between all tabs and windows from the same origin.
- The data does not expire. It remains after the browser restart and even OS reboot.
For instance, if you run this code...
- Es compartido entre todas las pestañas y ventanas del mismo orígen.
- Los datos no expiran. Persisten reinicios de navegador y hasta del sistema operativo.
Por ejemplo, si ejecutas éste código...
```js run
localStorage.setItem('test', 1);
```
...And close/open the browser or just open the same page in a different window, then you can get it like this:
... y cierras/abres el navegador, o simplemente abres la misma página en otra ventana, puedes cojer el ítem que hemos guardado de éste modo:
```js run
alert( localStorage.getItem('test') ); // 1
```
We only have to be on the same domain/port/protocol, the urlpath can be different.
Solo tenemos que estar en el mismo dominio/puerto/protocolo, la urlpuede ser distinta.
The`localStorage`is shared, so if we set the data in one window, the change becomes visiblein the other one.
`localStorage`es compartido, de modo que si guardamos datos en una ventana, el cambio es visibleen la otra.
##Object-like access
##Acceso tipo Objeto
We can also use a plain object way of getting/setting keys, like this:
Tambien podemos utilizar un modo de acceder/guardar claves del mismo modo que se hace con objetos, así:
```js run
//set key
//guarda una clave
localStorage.test = 2;
//get key
//coje una clave
alert( localStorage.test ); // 2
//remove key
//borra una clave
delete localStorage.test;
```
That's allowed for historical reasons, and mostly works, but generally not recommended for two reasons:
Esto se permite por razones históricas, y principalmente funciona, pero en general no se recomienda por dos motivos:
1.If the key is user-generated, it can be anything, like `length`or `toString`,or another built-in method of `localStorage`.In that case `getItem/setItem`work fine, while object-like access fails:
1.Si la clave es generada por el usuario, puede ser cualquier cosa, como `length`o `toString`,u otro método propio de `localStorage`.En este caso `getItem/setItem`funcionan correctamente, mientras que el acceso tipo objeto falla;
localStorage[key] = 5; // Error,no se puede asignar 'length'
```
2. Existe un evento `storage`, que se dispara cuando modificamos los datos. Este evento no se dispara si utilizamos el acceso tipo objeto. Lo veremos más tarde en este capítulo.
2. There's a `storage` event, it triggers when we modify the data. That event does not happen for object-like access. We'll see that later in this chapter.
## Looping over keys
## Iterando sobre las claves
Methods provideget/set/remove functionality. But how to get all the keys?
Los métodos proporcionan la funcionalidadget /set / remove. ¿Pero cómo conseguimos todas las claves?
Unfortunately, storage objects are not iterable.
Desafortunadamente, los objetos de almacenaje no son iterables.
alert( sessionStorage.getItem('test') ); //después de la recarga: 1
```
...But if you open the same page in another tab, and try again there, the code above returns `null`,meaning "nothing found".
... Pero si abres la misma página en otra pestaña, y lo intentas de nuevo, el código anterior devuelve `null`,que significa que no se ha encontrado nada.
That's exactly because`sessionStorage`is bound not only to the origin, but also to the browser tab. For that reason, `sessionStorage`is used sparingly.
Esto es exactamente porque`sessionStorage`no está vinculado solamente al orígen, sino también a la pestaña del navegador. Por ésta razón `sessionStorage`se usa relativamente poco.
##Storage event
##Evento storage
When the data gets updated in `localStorage`or`sessionStorage`, [storage](https://www.w3.org/TR/webstorage/#the-storage-event)event triggers, with properties:
Cuando los datos se actualizan en `localStorage`o en`sessionStorage`,el evento se dispara[storage](https://www.w3.org/TR/webstorage/#the-storage-event)con las propiedades:
- `key` –the key that was changed (null if`.clear()` is called).
- `oldValue` –the old value (`null`if the key is newly added).
- `newValue` –the new value (`null`if the key is removed).
- `url` –the urlof the document where the update happened.
- `storageArea` –either`localStorage`or `sessionStorage` object where the update happened.
- `key` –la clave que ha cambiado, (`null` si se llama`.clear()`).
- `oldValue` –el anterior valor (`null`si se añade una clave).
- `newValue` –el nuevo valor (`null`si se borra una clave).
- `url` –la urldel documento donde ha pasado la actualización.
- `storageArea` –bien el objeto`localStorage`o `sessionStorage`, donde se ha producido la actualización.
The important thing is: the event triggers on all`window`objects where the storage is accessible, except the one that caused it.
El hecho importante es: el evento se dispara en todos los objetos`window`donde el almacenaje es accesible, excepto en el que lo ha causado.
Let's elaborate.
Vamos a desarrollarlo.
Imagine, you have two windows with the same site in each. So`localStorage`is shared between them.
Imagina que tienes dos ventanas con el mismo sitio en cada una, de modo que`localStorage`es compartido entre ellas.
```online
You might want to open this page in two browser windows to test the code below.
Quizá quieras abrir ésta página en dos ventanas distintas para probar el código que sigue.
```
Now if both windows are listening for `window.onstorage`,then each one will react on updates that happened in the other one.
Si ambas ventanas están escuchando el evento `window.onstorage`,cada una reaccionará a las actualizaciones que pasen en la otra.
```js run
//triggers on updates made to the same storage from other documents
//se dispara en actualizaciones hechas en el mismo almacenaje, desde otros documentos
Please note that the event also contains: `event.url` --the urlof the document where the data was updated.
Hay que tener en cuenta que el evento también contiene: `event.url` --la urldel documento en que se actualizaron los datos.
Also,`event.storageArea`contains the storage object--the event is the same for both`sessionStorage`and `localStorage`,so`storageArea`references the one that was modified. We may event want to set something back in it, to "respond" to a change.
También que`event.storageArea`contiene el objeto de almacenaje--el evento es el mismo para`sessionStorage`y `localStorage`,de modo que`storageArea`referencia el que se modificó. Podemos hasta querer cambiar datos en él, para "responder" a un cambio.
**That allows different windows from the same origin to exchange messages.**
**Esto permite que distintas ventanas del mismo orígen puedan intercambiar mensajes.**
Modern browsers also support [Broadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API),the specialAPIfor same-origin inter-window communication, it's more full featured, but less supported. There are libraries that polyfill thatAPI, based on `localStorage`, that make it available everywhere.
Los navegadores modernos también soportan la [API deBroadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API),laAPIespecífica para la comunicación entre ventanas del mismo orígen. Es más completa, pero tiene menos soporte. Hay librerías que añaden polyfills para éstaAPI basados en `localStorage` para que se pueda utilizar en cualquier entorno.
##Summary
##Resumen
Web storage objects`localStorage`and `sessionStorage`allow to store key/value in the browser.
-Both `key` and `value` must be strings.
-The limit is 2mb+, depends on the browser.
-They do not expire.
-The data is bound to the origin (domain/port/protocol).
Los objetos de almacenaje web`localStorage`y `sessionStorage`permiten guardar pares de clave/valor en el navegador.
-Tanto la `clave` como el `valor` deben ser strings, cadenas de texto.
-El límite es de más de 2mb; depende del navegador.
-No expiran.
-Los datos están vinculados al orígen (domínio/puerto/protocolo).
| `localStorage` | `sessionStorage` |
|----------------|------------------|
|Shared between all tabs and windows with the same origin | Visible within a browser tab, including iframesfrom the same origin |
|Survives browser restart | Dies on tab close |
|Compartida entre todas las pestañas y ventanas que tengan el mismo orígen | Accesible en una pestaña del navegador, incluyendo iframesdel mismo origen |
|Sobrevive a reinicios del navegador | Muere al cerrar la pestaña |
API:
- `setItem(key, value)` --store key/value pair.
- `getItem(key)` --get the value by key.
- `removeItem(key)` --remove the key with its value.
- `clear()` --delete everything.
- `key(index)` --get the key on a given position.
- `length` --the number of stored items.
-Use `Object.keys`to get all keys.
-Can use the keys as object properties, in that case`storage`event doesn't trigger.
-Contains all the data about the operation, the document`url`and the storage object.
-Triggers on all`window`objects that have access to the storage except the one that generated it (within a tab for`sessionStorage`, globally for `localStorage`).
-Se dispara en las llamadas a`setItem`, `removeItem`, `clear`.
-Contiene todos los datos relativos a la operación, la`url`del documento y el objeto de almacenaje.
-Se dispara en todos los objetos`window`que tienen acceso al almacenaje excepto el que ha generado el evento (en una pestaña en el caso de`sessionStorage` o globalmente en el caso de `localStorage`).
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.