Skip to content

Commit aec1a3a

Browse files
authored
Merge pull request #82 from arnaugiralt/patch-1
LocalStorage, sessionStorage
2 parents fd721d0 + 599e93f commit aec1a3a

File tree

1 file changed

+100
-102
lines changed

1 file changed

+100
-102
lines changed
Lines changed: 100 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,80 @@
11
# LocalStorage, sessionStorage
22

3-
Web storage objects `localStorage` and `sessionStorage` allow to save key/value pairs in the browser.
3+
Los objetos de almacenaje web `localStorage` y `sessionStorage` permiten guardar pares de clave/valor en el navegador.
44

5-
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.
5+
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.
66

7-
We already have cookies. Why additional objects?
7+
Ya tenemos cookies. ¿Por qué tener objetos adicionales?
88

9-
- Unlike cookies, web storage objects are not sent to server with each request. Because of that, we can store much more. Most browsers allow at least 2 megabytes of data (or more) and have settings to configure that.
10-
- The server can't manipulate storage objects via HTTP headers, everything's done in JavaScript.
11-
- 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.
9+
- Al contrario que las cookies, 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 megabytes de datos (o más) y tienen opciones para configurar éstos límites.
10+
- El servidor no puede manipular los objetos de almacenaje via cabezeras HTTP, todo se hace via JavaScript.
11+
- 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.
1212

13-
Both storage objects provide same methods and properties:
13+
Ámbos objetos de almacenaje proveen los mismos métodos y propiedades:
1414

15-
- `setItem(key, value)` -- store key/value pair.
16-
- `getItem(key)` -- get the value by key.
17-
- `removeItem(key)` -- remove the key with its value.
18-
- `clear()` -- delete everything.
19-
- `key(index)` -- get the key on a given position.
20-
- `length` -- the number of stored items.
15+
- `setItem(clave, valor)` -- almacenar un par clave/valor.
16+
- `getItem(clave)` -- obtener el valor por medio de la clave.
17+
- `removeItem(clave)` -- eliminar la clave y su valor.
18+
- `clear()` -- borrar todo.
19+
- `key(índice)` -- obtener la clave de una posición dada.
20+
- `length` -- el número de ítems almacenados.
2121

22-
Let's see how it works.
22+
Vamos a ver cómo funciona.
2323

24-
## localStorage demo
24+
## Demo de localStorage
2525

26-
The main features of `localStorage` are:
26+
Las principales funcionalidades de `localStorage` son:
2727

28-
- Shared between all tabs and windows from the same origin.
29-
- The data does not expire. It remains after the browser restart and even OS reboot.
30-
31-
For instance, if you run this code...
28+
- Es compartido entre todas las pestañas y ventanas del mismo orígen.
29+
- Los datos no expiran. Persisten reinicios de navegador y hasta del sistema operativo.
3230

31+
Por ejemplo, si ejecutas éste código...
3332
```js run
3433
localStorage.setItem('test', 1);
3534
```
3635

37-
...And close/open the browser or just open the same page in a different window, then you can get it like this:
36+
... 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:
3837

3938
```js run
4039
alert( localStorage.getItem('test') ); // 1
4140
```
4241

43-
We only have to be on the same domain/port/protocol, the url path can be different.
42+
Solo tenemos que estar en el mismo dominio/puerto/protocolo, la url puede ser distinta.
4443

45-
The `localStorage` is shared, so if we set the data in one window, the change becomes visible in the other one.
44+
`localStorage` es compartido, de modo que si guardamos datos en una ventana, el cambio es visible en la otra.
4645

47-
## Object-like access
46+
## Acceso tipo Objeto
4847

49-
We can also use a plain object way of getting/setting keys, like this:
48+
Tambien podemos utilizar un modo de acceder/guardar claves del mismo modo que se hace con objetos, así:
5049

5150
```js run
52-
// set key
51+
// guarda una clave
5352
localStorage.test = 2;
5453

55-
// get key
54+
// coje una clave
5655
alert( localStorage.test ); // 2
5756

58-
// remove key
57+
// borra una clave
5958
delete localStorage.test;
6059
```
6160

62-
That's allowed for historical reasons, and mostly works, but generally not recommended for two reasons:
61+
Esto se permite por razones históricas, y principalmente funciona, pero en general no se recomienda por dos motivos:
6362

64-
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:
63+
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;
6564
```js run
6665
let key = 'length';
67-
localStorage[key] = 5; // Error, can't assign length
66+
localStorage[key] = 5; // Error, no se puede asignar 'length'
6867
```
68+
69+
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.
6970

70-
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.
71-
72-
## Looping over keys
71+
## Iterando sobre las claves
7372

74-
Methods provide get/set/remove functionality. But how to get all the keys?
73+
Los métodos proporcionan la funcionalidad get / set / remove. ¿Pero cómo conseguimos todas las claves?
7574

76-
Unfortunately, storage objects are not iterable.
75+
Desafortunadamente, los objetos de almacenaje no son iterables.
7776

78-
One way is to use "array-like" iteration:
77+
Una opción es utilizar iteración "tipo array":
7978

8079
```js run
8180
for(let i=0; i<localStorage.length; i++) {
@@ -84,29 +83,29 @@ for(let i=0; i<localStorage.length; i++) {
8483
}
8584
```
8685

87-
Another way is to use object-specific `for key in localStorage` loop.
86+
Otra opción es utilizar el loop específico para objetos `for key in localStorage`.
8887

89-
That iterates over keys, but also outputs few built-in fields that we don't need:
88+
Ésta opción itera sobre las claves, pero también devuelve campos propios de `localStorage` que no necesitamos:
9089

9190
```js run
92-
// bad try
91+
// mal intento
9392
for(let key in localStorage) {
94-
alert(key); // shows getItem, setItem and other built-in stuff
93+
alert(key); // muestra getItem, setItem y otros campos que no nos interesan
9594
}
9695
```
9796

98-
...So we need either to filter fields from the prototype with `hasOwnProperty` check:
97+
... De modo que necesitamos o bien filtrar campos des del prototipo con la validación `hasOwnProperty`:
9998

10099
```js run
101100
for(let key in localStorage) {
102101
if (!localStorage.hasOwnProperty(key)) {
103-
continue; // skip keys like "setItem", "getItem" etc
102+
continue; // se salta claves como "setItem", "getItem" etc
104103
}
105104
alert(`${key}: ${localStorage.getItem(key)}`);
106105
}
107106
```
108107

109-
...Or just get the "own" keys with `Object.keys` and then loop over them if needed:
108+
... O simplemente acceder a las claves "propias" con `Object.keys` y iterar sobre éstas si es necesario:
110109

111110
```js run
112111
let keys = Object.keys(localStorage);
@@ -115,91 +114,90 @@ for(let key of keys) {
115114
}
116115
```
117116

118-
The latter works, because `Object.keys` only returns the keys that belong to the object, ignoring the prototype.
119-
117+
Esta última opción funciona, ya que `Object.keys` solo devuelve las claves que pertenecen al objeto, ignorando el prototipo.
120118

121-
## Strings only
119+
## Solo strings
122120

123-
Please note that both key and value must be strings.
121+
Hay que tener en cuenta que tanto la clave como el valor deben ser strings.
124122

125-
If we any other type, like a number, or an object, it gets converted to string automatically:
123+
Cualquier otro tipo, como un número o un objeto, se convierte a cadena de texto automáticamente:
126124

127125
```js run
128126
sessionStorage.user = {name: "John"};
129127
alert(sessionStorage.user); // [object Object]
130128
```
131129

132-
We can use `JSON` to store objects though:
130+
A pesar de eso, podemos utilizar `JSON` para almacenar objetos:
133131

134132
```js run
135133
sessionStorage.user = JSON.stringify({name: "John"});
136134
137-
// sometime later
135+
// en algún momento más tarde
138136
let user = JSON.parse( sessionStorage.user );
139137
alert( user.name ); // John
140138
```
141139

142-
Also it is possible to stringify the whole storage object, e.g. for debugging purposes:
140+
También es posible pasar a texto todo el objeto de almacenaje, por ejemplo para debugear:
143141

144142
```js run
145-
// added formatting options to JSON.stringify to make the object look nicer
143+
// se ha añadido opciones de formato a JSON.stringify para que el objeto se lea mejor
146144
alert( JSON.stringify(localStorage, null, 2) );
147145
```
148146

149147

150148
## sessionStorage
151149

152-
The `sessionStorage` object is used much less often than `localStorage`.
150+
El objeto `sessionStorage` se utiliza mucho menos que `localStorage`.
153151

154-
Properties and methods are the same, but it's much more limited:
152+
Las propiedades y métodos son los mismos, pero es mucho más limitado:
155153

156-
- The `sessionStorage` exists only within the current browser tab.
157-
- Another tab with the same page will have a different storage.
158-
- But it is shared between iframes in the tab (assuming they come from the same origin).
159-
- The data survives page refresh, but not closing/opening the tab.
154+
- `sessionStorage` solo existe dentro de la pestaña actual.
155+
- Otra pestaña con la misma página tendrá un almacenaje distinto.
156+
- Pero se comparte entre iframes en la pestaña (asumiendo que tengan el mismo orígen).
157+
- Los datos sobreviven un refresco de página, pero no cerrar/abrir la pestaña.
160158

161-
Let's see that in action.
159+
Vamos a verlo en acción.
162160

163-
Run this code...
161+
Ejecuta éste código...
164162

165163
```js run
166164
sessionStorage.setItem('test', 1);
167165
```
168166

169-
...Then refresh the page. Now you can still get the data:
167+
... Y recarga la página. Aún puedes acceder a los datos:
170168

171169
```js run
172-
alert( sessionStorage.getItem('test') ); // after refresh: 1
170+
alert( sessionStorage.getItem('test') ); // después de la recarga: 1
173171
```
174172

175-
...But if you open the same page in another tab, and try again there, the code above returns `null`, meaning "nothing found".
173+
... 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.
176174

177-
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.
175+
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.
178176

179-
## Storage event
177+
## Evento storage
180178

181-
When the data gets updated in `localStorage` or `sessionStorage`, [storage](https://www.w3.org/TR/webstorage/#the-storage-event) event triggers, with properties:
179+
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:
182180

183-
- `key`the key that was changed (null if `.clear()` is called).
184-
- `oldValue`the old value (`null` if the key is newly added).
185-
- `newValue`the new value (`null` if the key is removed).
186-
- `url`the url of the document where the update happened.
187-
- `storageArea`either `localStorage` or `sessionStorage` object where the update happened.
181+
- `key`la clave que ha cambiado, (`null` si se llama `.clear()`).
182+
- `oldValue`el anterior valor (`null` si se añade una clave).
183+
- `newValue`el nuevo valor (`null` si se borra una clave).
184+
- `url`la url del documento donde ha pasado la actualización.
185+
- `storageArea`bien el objeto `localStorage` o `sessionStorage`, donde se ha producido la actualización.
188186

189-
The important thing is: the event triggers on all `window` objects where the storage is accessible, except the one that caused it.
187+
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.
190188

191-
Let's elaborate.
189+
Vamos a desarrollarlo.
192190

193-
Imagine, you have two windows with the same site in each. So `localStorage` is shared between them.
191+
Imagina que tienes dos ventanas con el mismo sitio en cada una, de modo que `localStorage` es compartido entre ellas.
194192

195193
```online
196-
You might want to open this page in two browser windows to test the code below.
194+
Quizá quieras abrir ésta página en dos ventanas distintas para probar el código que sigue.
197195
```
198196

199-
Now if both windows are listening for `window.onstorage`, then each one will react on updates that happened in the other one.
197+
Si ambas ventanas están escuchando el evento `window.onstorage`, cada una reaccionará a las actualizaciones que pasen en la otra.
200198

201199
```js run
202-
// triggers on updates made to the same storage from other documents
200+
// se dispara en actualizaciones hechas en el mismo almacenaje, desde otros documentos
203201
window.onstorage = event => {
204202
if (event.key != 'now') return;
205203
alert(event.key + ':' + event.newValue + " at " + event.url);
@@ -208,40 +206,40 @@ window.onstorage = event => {
208206
localStorage.setItem('now', Date.now());
209207
```
210208

211-
Please note that the event also contains: `event.url` -- the url of the document where the data was updated.
209+
Hay que tener en cuenta que el evento también contiene: `event.url` -- la url del documento en que se actualizaron los datos.
212210

213-
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.
211+
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.
214212

215-
**That allows different windows from the same origin to exchange messages.**
213+
**Esto permite que distintas ventanas del mismo orígen puedan intercambiar mensajes.**
216214

217-
Modern browsers also support [Broadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API), the special API for same-origin inter-window communication, it's more full featured, but less supported. There are libraries that polyfill that API, based on `localStorage`, that make it available everywhere.
215+
Los navegadores modernos también soportan la [API de Broadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API), la API especí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 ésta API basados en `localStorage` para que se pueda utilizar en cualquier entorno.
218216

219-
## Summary
217+
## Resumen
220218

221-
Web storage objects `localStorage` and `sessionStorage` allow to store key/value in the browser.
222-
- Both `key` and `value` must be strings.
223-
- The limit is 2mb+, depends on the browser.
224-
- They do not expire.
225-
- The data is bound to the origin (domain/port/protocol).
219+
Los objetos de almacenaje web `localStorage` y `sessionStorage` permiten guardar pares de clave/valor en el navegador.
220+
- Tanto la `clave` como el `valor` deben ser strings, cadenas de texto.
221+
- El límite es de más de 2mb; depende del navegador.
222+
- No expiran.
223+
- Los datos están vinculados al orígen (domínio/puerto/protocolo).
226224

227225
| `localStorage` | `sessionStorage` |
228226
|----------------|------------------|
229-
| Shared between all tabs and windows with the same origin | Visible within a browser tab, including iframes from the same origin |
230-
| Survives browser restart | Dies on tab close |
227+
| Compartida entre todas las pestañas y ventanas que tengan el mismo orígen | Accesible en una pestaña del navegador, incluyendo iframes del mismo origen |
228+
| Sobrevive a reinicios del navegador | Muere al cerrar la pestaña |
231229

232230
API:
233231

234-
- `setItem(key, value)` -- store key/value pair.
235-
- `getItem(key)` -- get the value by key.
236-
- `removeItem(key)` -- remove the key with its value.
237-
- `clear()` -- delete everything.
238-
- `key(index)` -- get the key on a given position.
239-
- `length` -- the number of stored items.
240-
- Use `Object.keys` to get all keys.
241-
- Can use the keys as object properties, in that case `storage` event doesn't trigger.
232+
- `setItem(clave, valor)` -- guarda pares clave/valor.
233+
- `getItem(clave)` -- coje el valor de una clave.
234+
- `removeItem(clave)` -- borra una clave con su valor.
235+
- `clear()` -- bórralo todo.
236+
- `key(índice)` -- coje la clave en una posición determinada.
237+
- `length` -- el número de ítems almacenados.
238+
- Utiliza `Object.keys` para conseguir todas las claves.
239+
- Puede utilizar las claves como propiedades de objetor, pero en ese caso el evento `storage` no se dispara
242240

243-
Storage event:
241+
Evento storage:
244242

245-
- Triggers on `setItem`, `removeItem`, `clear` calls.
246-
- Contains all the data about the operation, the document `url` and the storage object.
247-
- 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`).
243+
- Se dispara en las llamadas a `setItem`, `removeItem`, `clear`.
244+
- Contiene todos los datos relativos a la operación, la `url` del documento y el objeto de almacenaje.
245+
- 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`).

0 commit comments

Comments
 (0)