HTML Web 存储是一种机制,可帮助 Web 应用程序在用户浏览器中本地存储数据。
Web 存储的类型
HTML 引入了两种机制,类似于 HTTP 会话 cookie,用于在客户端存储结构化数据,而无需将其发送到服务器。
- 会话存储
- 本地存储
要在 Web 应用程序中使用会话存储或本地存储,我们可以分别通过 window.sessionStorage 和 window.localStorage 属性访问它们。
HTML Web 存储示例
以下是一些示例,展示了 HTML 中 Web 存储的不同方式。
探索我们最新的在线课程,按照自己的节奏学习新技能。注册并成为认证专家,以提升您的职业生涯。
会话存储
会话存储是临时的,当页面会话结束时会被清除,这在浏览器选项卡或窗口关闭时发生。存储在会话存储中的数据特定于每个选项卡或窗口。
HTML5 引入了 sessionStorage 属性,站点将使用该属性将数据添加到会话存储中,并且在该窗口中打开的同一站点(即会话)中的任何页面都可以访问它,一旦您关闭窗口,会话就会丢失。
例子以下是设置会话变量并访问该变量的代码。
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
if( sessionStorage.hits ){
sessionStorage.hits = Number(sessionStorage.hits) +1;
} else {
sessionStorage.hits = 1;
}
document.write("Total Hits :" + sessionStorage.hits );
</script>
<p>
Refresh the page to increase number of hits.
</p>
<p>
Close the window and open it again and check
the result.
</p>
</body>
</html>
本地存储
本地存储专为跨多个窗口的存储而设计,并持续到当前会话之后。它不会过期并保留在浏览器中,直到用户或 Web 应用程序手动删除它。特别是,出于性能原因,Web 应用程序可能希望在客户端存储兆字节的用户数据,例如整个用户创作的文档或用户邮箱。
同样,cookie 不能很好地处理这种情况,因为它们会随着每个请求一起传输。
HTML5 引入了 localStorage 属性,该属性将用于访问页面的本地存储区域,没有时间限制,并且只要您使用该页面,此本地存储都将可用。
例以下是设置本地存储变量并在每次访问此页面时访问该变量的代码,甚至在下次打开窗口时也是如此;
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
} else {
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>
Refresh the page to increase number of hits.
</p>
<p>
Close the window and open it again and check
the result.
</p>
</body>
</html>
删除 Web 存储
在本地计算机上存储敏感数据可能很危险,并可能留下安全漏洞。会话存储数据将在会话终止后立即被浏览器删除。
但是,要清除本地存储设置,我们需要调用 localStorage.remove('key'); 其中 'key' 是我们要删除的值的键。如果我们想清除所有设置,可以调用 localStorage.clear() 方法。
例以下是清除完整本地存储的代码;
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
localStorage.clear();
// Reset number of hits.
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
} else {
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>
Refreshing the page would not to increase
hit counter.
</p>
<p>
Close the window and open it again and check
the result.
</p>
</body>
</html>
Reson对birng Web Storage over Cookies的共鸣
引入网络存储是为了克服 cookie 的以下缺点。
- 每个 HTTP 请求都包含 Cookie,从而通过传输相同的数据来减慢您的 Web 应用程序的速度。
- 每个 HTTP 请求都包含 Cookie,从而通过 Internet 发送未加密的数据。
- Cookie 限制为大约 4 KB 的数据。不足以存储所需的数据。