HTML5的本地存储

Web Storage 提供了两种存储类型API接口:localStorage 和sessionStorage

二者的简单区别

名称 localStorage sessionStorage
生命周期 除非用户删除,否则永久保存 网页关闭,生命周期结束
存储位置 本地 浏览器端
     

Storage事件监听:

只需要使用HTML5 Web Storage API内置的事件监听器对事件进行控制

addEventListener()

要监听的事件代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>使用WebStorage存储事件监听实例-操作LocalStorage数据</title>
    
    <script type="text/javascript">
      window.onload = function(){                   /*对storage对象进行了三次操作 */
          localStorage.clear();
          localStorage.setItem("userData","storage demo");
          localStorage.setItem("userData","storage event demo");
      }
    </script>
  </head>
  <body></body>
</html>

监听器

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>监听localStorage事件 </title>
    <script type="text/javascript">
      window.onload = function(){
            window.addEventListener("storage",function(e){
                console.log(e);
                },true);
          }
    </script>
  </head>
  <body></body>
</html>

监听结果:数据被更改了3次

HTML5的本地存储