LocalStorage, SessionStorage

JavaScript LocalStorage, SessionStorage (JavaScript LocalStorage、SessionStorage)

LocalStorage and sessionStorage are web storage objects, allowing developers to save key-value pairs in the browser. (LocalStorage和sessionStorage是Web存储对象,允许开发人员在浏览器中保存键值对。)

The most interesting thing about them is that the data survives a page refresh and a full restart of the browser. (它们最有趣的地方在于,数据在页面刷新和浏览器完全重新启动后仍然存在。)

Both of the storage objects include the same properties and methods:

  • setItem(key, value) – keep the key/value pair. (- setItem (key, value) –保留键/值对。)

  • getItem(key) – receive the value by key. (- getItem (key) –通过key接收值。)

  • removeItem(key) –delete the key, along with its value. (- removeItem (key) -删除键及其值。)

  • clear()– remove everything. (- clear () –移除所有物品。)

  • key(index) – receive the key in a specific position. (-钥匙(索引) –在特定位置接收钥匙。)

  • length – the quantity of the stored items. (-长度–存储项目的数量。)

So, it is a Map collection (setItem/getItem/removeItem), which also allows accessing by index with key(index). (因此,它是一个Map集合( setItem/getItem/removeItem ) ,它还允许使用key (index)通过index进行访问。)

LocalStorage Demo

LocalStorage Demo (LocalStorage演示)

The localStorage has the following features:

It is shared between all the tabs and windows from the same origin. The data remains after the browser restarts. It doesn’t expire even after OS reboot. (它在来自同一原点的所有选项卡和窗口之间共享。 浏览器重新启动后,数据仍会保留。 即使在操作系统重新启动后也不会过期。)

Here is an example of using localStorage:

localStorage.setItem('test', 2);

So, if you run the code above and open/close the browser or even open the same page in another window, you will get it as follows:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     alert(localStorage.getItem('test')); 
   </script>
 </body>
</html>

The localStorage is shared between the overall windows with the same origin. So, setting the data in one window makes the change visible in another one. (LocalStorage在具有相同原点的整个窗口之间共享。因此,在一个窗口中设置数据会使更改在另一个窗口中可见。)

Object-like Access

Object-like Access (类对象访问)

A plain object can also be used without getting/setting keys, like here:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // set key
(SET键)
     localStorage.test = 2;
     // get key
(取得金钥)
     alert(localStorage.test); // 2        
     // remove key
(移除密钥)
     delete localStorage.test;
   </script>
 </body>
</html>

This code works but, generally, it is not recommended. (此代码有效,但一般不推荐使用。)

Looping Over the keys

Looping Over the keys (在钥匙上循环)

Storage objects are not iterable. (存储对象不可迭代。)

One of the ways is looping them as over an array, like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     for(let j = 0; j < localStorage.length; j++) {
       let key = localStorage.key(j);
       alert(`${key}: ${localStorage.getItem(key)}`);
     }
   </script>
 </body>
</html>

The next way is to use for key in localStorage loop, just as doing with regular objects. (下一种方法是在localStorage循环中使用for键,就像使用常规对象一样。)

That iterates over keys but also outputs some built-in fields that you may not need:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // bad try
(//错误尝试)
     for(let key in localStorage) {
       alert(key); // shows getItem, setItem and other built-in things
     }
   </script>
 </body>
</html>

So, it is necessary to filter fields from the prototype using hasOwnProperty check, like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     for(let key in localStorage) {
       if(!localStorage.hasOwnProperty(key)) {
         continue; // skip keys like "setItem", "getItem" etc
       }
       alert(`${key}: ${localStorage.getItem(key)}`);
     }
   </script>
 </body>
</html>

Another option is to get the own keys using Object.keys and loop over them, if it is necessary, like here:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     let keys = Object.keys(localStorage);
     for(let key of keys) {
       alert(`${key}: ${localStorage.getItem(key)}`);
     }
   </script>
 </body>
</html>

Only Strings

Only Strings (仅字符串)

Both the key and the value should be strings. (键和值都应为字符串。)

In case there is another type (for example, a number or an object), it will automatically be converted into a string, like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     sessionStorage.user = {
       name: "Jack"
     };
     alert(sessionStorage.user); // [object Object]
   </script>
 </body>
</html>

For storing objects, you can also use JSON:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     sessionStorage.user = JSON.stringify({
       name: "Jack"
     });
     // sometime later
(//稍后)
     let user = JSON.parse(sessionStorage.user);
     alert(user.name); // Jack
   </script>
 </body>
</html>

It is also possible to stringify the overall storage object (for example, for debugging):

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // added formatting options to JSON.stringify to make the object look nicer
(//向JSON.stringify添加了格式选项,使对象看起来更漂亮)
     alert(JSON.stringify(localStorage, null, 2));
   </script>
 </body>
</html>

SessionStorage

SessionStorage

The sessionStorage is used not as often as localStorage. But their properties and methods are the same. However, sessionStorage is more limited:

  • It exists only within the current browser tab. (-它仅存在于当前的浏览器选项卡中。)

  • A different tab with the same page will have another storage. (-具有相同页面的不同选项卡将具有另一个存储空间。)

  • It is shared between iframes in the same tab. (-它在同一选项卡中的iframe之间共享。)

  • The data survives page refresh. (-数据在页面刷新后仍然存在。)

The code for running localStorage is the following:

sessionStorage.setItem('test', 2);

You will still get the data after refreshing the page:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     alert(sessionStorage.getItem('test')); // after refresh: 2
   </script>
 </body>
</html>

But opening the same page in another tab will return null, which means “nothing found”. The reason is that sessionStorage is bound to both the origin and the browser tab. So, it is used sparingly. (但是,在另一个选项卡中打开相同的页面将返回null ,这意味着“未找到任何内容”。原因是sessionStorage同时绑定到源和浏览器选项卡。因此,它使用得很节约。)

Storage Event

Storage Event (存储事件)

Once the data is updated in the localStorage or the sessionStorage, storage event occurs, with these properties:

  • key – the changed key (null in case .clear() is called). (- key –更改的密钥(如果调用.clear () ,则为null )。)

  • oldValue – the old value (null in case the new key is added). (- oldValue –旧值(如果添加了新键,则为空)。)

  • newValue – the new value (null in case the key is removed). (- newValue –新值(如果键被删除,则为null )。)

  • url – the document URL where the update occurred. (- url –发生更新的文档URL。)

  • storageArea – the localStorage or the sessionStorage object where the update occurred. (- storageArea –发生更新的localStorage或sessionStorage对象。)

The storage event happens on all the window objects where the storage is accessible, except the one causing it. (存储事件发生在可访问存储的所有窗口对象上,导致存储事件的窗口对象除外。)

Let’s take a look at an example:

window.onstorage = event => { // same as window.addEventListener('storage', () => {
 if (event.key != 'now') { 
   return;
 }
 alert(event.key + ':' + event.newValue + " at " + event.url);
};
localStorage.setItem('now', Date.now());

Also, modern browsers support the specific API, known as Broadcast channel API, used for same-origin inter-window communication. There are libraries that polyfill it, based on the localStorage, making it available anywhere. (此外,现代浏览器支持用于同源窗口间通信的特定API ,即广播通道API。有基于localStorage的polyfill库,使其在任何地方都可用。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部