57

在我以前的网站上,我曾经使用 cookie 仅在第一次访问时显示主页。效果很好(例如,请参见此处),但是今天使用 cookie 并不那么流行,所以我想尽可能地避免它。

现在,我的新网站项目几乎总是通过 javascript 启动 pre-home(显示模态框),所以我不需要在服务器端执行任何操作。我正在考虑使用 HTML5 localStorage 而不是 cookie,如果浏览器没有 localStorage,则使用 cookie。这是一个好主意吗?在可用性、隐私保护和网站性能方面有什么影响?

使用 localStorage 将提高禁用 cookie 的用户的可用性。但我知道某些 HTML5 功能只能在某些浏览器中选择加入(如地理定位)。任何浏览器上的 localStorage 是否有类似的限制?如果 localStorage 可用但我的站点已停用,是否会出现 JS 错误?

4

4 回答 4

83

Usability

The user will not know if you are using localStorage or a cookie. If a user disable cookies, localStorage will not work either.

Performance

There is no noticeable speed difference between the two methods.

sessionStorage

sessionStorage is only for that browser tab's session. If you close the tab, the session will be lost and the data will be lost too, it's similar to a session variable on any backend language.

localStorage

localStorage will be available for any tab or window in the browser, and will exist until it is deleted by the user or the program. Unlike a cookie, you cannot setup expiration. localStorage has a much larger storage limit as well.

Your Questions

  1. You are not using this data server side, so you don't need a cookie. localStorage is never sent to the server unlike a cookie.
  2. If the user disables the cookies, localStorage will not work either.

Fallback Example

You can use a Modernizr to verify if localStorage is available and if not, use store a cookie instead.

if (Modernizr.localstorage) {
    // supports HTML5 Storage :D
} else {
    // does not support HTML5 Storage :(
}

You can also forego Modernizr and use the check typeof Storage !== 'undefined'.

于 2013-05-31T11:09:54.053 回答
32

比较 LS 和 cookie 就是比较苹果和橙子。

Cookies 和 LS 是完全不同的东西,用途不同。LS 是一种工具,它允许您的客户端(javascript 代码)在本地存储其数据,而无需将其传输到服务器。Cookies 是客户端与服务器之间通信的工具。cookie 的全部意义在于随每个请求一起发送。

过去,cookie 经常被滥用来模拟本地存储,因为这是 javascript 应用程序向客户端硬盘驱动器写入任何内容的唯一可能性。但通常 LS 不能替代 cookie,所以如果您需要客户端和服务器都应该读写的东西,请使用 cookie,而不是 LS。

于 2013-05-31T11:20:56.360 回答
7

需要补充一点的是,与通常跨协议共享的 cookie 不同,存储坚持同源策略。因此,站点共享相同的域但托管在不同协议上的站点不共享存储的数据。

假设您的网站需要跨 http 和 https 工作。例如,当用户点击“购买链接”时,他们将登陆 https 安全结帐,然后结帐将无法检索以前存储在 http 站点上的数据,即使他们共享同一个域。

于 2016-04-18T17:23:46.433 回答
0

服务器读取 localStorage 看起来并不容易。不过,这可能会派上用场,因为您知道您的数据都是客户端的,因此可以避免被嗅探。

Cookies 不能被改写,只能添加和读取:

alert(document.cookie);
document.cookie = "nope";
alert(document.cookie);
于 2013-05-31T11:02:46.867 回答