前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JS:Web Storage API(localStorage、sessionStorage)

JS:Web Storage API(localStorage、sessionStorage)

作者头像
WEBJ2EE
发布2020-05-09 11:00:21
1.4K0
发布2020-05-09 11:00:21
举报
文章被收录于专栏:WebJ2EEWebJ2EE

目录

1. 浏览器兼容性

2. localStorage

3. sessionStorage

Web Storage API 提供了存储机制,通过该机制,浏览器可以安全地存储键值对,比使用 cookie 更加直观。Web Storage 包含如下两种机制:

  • sessionStorage
  • localStorage

1. 浏览器兼容性

2. localStorage

  • localStorage 存储的数据是永久性的,除非通过 JavaScript 删除或者用户清除浏览器缓存,否则数据将一直保留在用户的电脑上,永不过期
  • localStorage 的作用域受同源策略限制(协议、主机名、端口),同源的文档间共享同样的localStorage数据;
  • localStorage 的作用域也受浏览器厂商限制,Chrome 与 Firefox 中的 localStorage 无法共享;
  • localStorage 中只能存储字符串!!!!
  • 支持 storage 存储事件;

API:

代码语言:javascript
复制
localStorage.setItem('myCat', 'Tom'); // 增加一个 localStorage 项
let cat = localStorage.getItem('myCat'); // 读取 localStorage 项
localStorage.removeItem('myCat'); // 移除 localStorage 项
localStorage.clear(); // 清空所有 localStorage 项

示例:

index.html:

代码语言:javascript
复制
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>Web Storage API example</title>

    <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Bitter|Ubuntu+Mono' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="style.css">
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>

  <body>
  <div class="wrapper">
    <h1>Web storage</h1>

    <p>This example is designed to demonstrate usage of the <a href="http://dev.w3.org/html5/webstorage/">W3C Web Storage API</a>. It should work as far back as IE8. Choose custom background colours, logos and fonts from the below drop down menus, then try closing and reopening the page — you will find that your choices are remembered, as they are stored using Web Storage. You can also visit the <a href="event.html" target="_blank">storage event output</a> (opens in new tab). Open this, change some values in the index page, then look at the events page — you'll see the storage changes reported.</p>

    <form>
      <div>
        <label for="bgcolor">Choose background color:</label>
      <input class="color" id="bgcolor" value="FF0000">
      </div>
      <div>
        <label for="font">Choose font style:</label>
        <select id="font">
          <option value="'Open Sans Condensed', sans-serif" selected>Sans-serif</option>
          <option value="'Bitter', serif">Serif</option>
          <option value="'Ubuntu Mono'">Monospace</option>
        </select>
      </div>
      <div>
        <label for="image">Choose image:</label>
        <select id="image">
          <option value="images/firefoxos.png" selected>Firefox</option>
          <option value="images/crocodile.png">Crocodile</option>
          <option value="images/tortoise.png">Tortoise</option>
        </select>
      </div>
    </form>

    <footer></footer>
    <img src="images/firefoxos.png">
  </div>
  </body>
  <script src="jscolor/jscolor.js"></script>
  <script src="main.js"></script>
</html>

main.js:

代码语言:javascript
复制
var htmlElem = document.querySelector('html');
var pElem = document.querySelector('p');
var imgElem = document.querySelector('img');

var bgcolorForm = document.getElementById('bgcolor');
var fontForm = document.getElementById('font');
var imageForm = document.getElementById('image');

if(!localStorage.getItem('bgcolor')) {
  populateStorage();
} else {
  setStyles();
}

function populateStorage() {
  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
  localStorage.setItem('font', document.getElementById('font').value);
  localStorage.setItem('image', document.getElementById('image').value);

  setStyles();
}

function setStyles() {
  var currentColor = localStorage.getItem('bgcolor');
  var currentFont = localStorage.getItem('font');
  var currentImage = localStorage.getItem('image');

  document.getElementById('bgcolor').value = currentColor;
  document.getElementById('font').value = currentFont;
  document.getElementById('image').value = currentImage;

  htmlElem.style.backgroundColor = '#' + currentColor;
  pElem.style.fontFamily = currentFont;
  imgElem.setAttribute('src', currentImage);
}

bgcolorForm.onchange = populateStorage;
fontForm.onchange = populateStorage;
imageForm.onchange = populateStorage;

3. sessionStorage

sessionStorage 的工作方式和 localStorage 很接近,不同之处在于储存数据的有效期与作用域;

  • A page session lasts as long as the browser is open, and survives over page reloads and restores。
    • 浏览器(或选项卡)刷新时,不会引起 sessionStorage 销毁
  • Closing a tab/window ends the session and clears objects in sessionStorage.
    • 会在浏览器(或选项卡)被关闭时销毁。
  • The sessionStorage property accesses a session Storage object for the current origin.
    • 同源策略是根本。
  • Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
    • 如果手动打开多个Tab或窗口,即便同源,也是不同的 sessionStorage。
  • Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
    • <a href="同源页面" target="_self">跳转</a>
    • <a href="同源页面" target="_blank">跳转</a>
    • window.location.href = '同源页面'
    • window.location.replace('同源页面')
    • window.open('同源页面')
    • 同一浏览器Tab页下的两个同源iframe

共享 sessionStorage 数据

示例:sessionStorage 存储应用状态;

代码语言:javascript
复制
 <!DOCTYPE html>
<html>
<head>
  <title></title>
  <style type="text/css">
</style>
</head>
<body>
    Counter: <input id="counter" value="0" disabled />
    <button onclick="add()">+</button>
    <button onclick="sub()">-</button>

    <hr/>

    <button onclick="windowOpenNew()">window.open</button>
    <a href="./html.html" target="_self">href</a>
    <script>
      function windowOpenNew(){
        window.open("./html.html");
      }
</script>

    <script>
      function add(){
        const o = document.getElementById("counter");
        o.value = Number(o.value)+1;
        save(o.value);
      }

      function sub(){
        const o = document.getElementById("counter");
        o.value = Number(o.value)+1;
        save(o.value);
      }

      function save(v){
        sessionStorage.setItem("counter", v);
      }

      function restore(){
        const o = document.getElementById("counter");
        o.value = sessionStorage.getItem("counter");
      }

      window.onload = function(){
        restore();
      }
</script>
</body>
</html>
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 WebJ2EE 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档