Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端存储技术 #50

Closed
xwchris opened this issue Aug 21, 2018 · 0 comments
Closed

前端存储技术 #50

xwchris opened this issue Aug 21, 2018 · 0 comments

Comments

@xwchris
Copy link
Owner

xwchris commented Aug 21, 2018

浏览器中的存储分为多种方式,它们的应用常见各不相同。本文部分参考cookie规范-RFC 6265

Cookie

cookie简介

cookie是一种很古老的技术了,然而直到现在,它的应用依旧非常广泛,多用来保持用户的登录状态等。

cookie一般情况下由服务器生成,它最大为4k左右,平时使用也涉及到用js进行cookie操作

cookie操作

用js设置cookie可以通过给document.cookie赋值进行设置。可设置的值包括键值对、作用域、过期时间等设置形式如下:

document.cookie = 'name=xxx;domain=xwchris.me;path=/;max-age=1000'

domainpath是cookie的作用域,cookie只在该作用域下有效,不设置domain和path的时候,默认是设置cookie页面的域名和路径。

cookie过期时间

设置cookie过期时间可以使用两种方法:

  • expires: cookie过期时间点它接收一个GMT格式时间
  • max-age: 相对当前时间过期所需要的秒(S)数

expiresmax-age同时存在的时候,以max-age为准。当没有设置过期时间的时候,默认过期时间是到浏览器关闭的时候,关闭浏览器则该cookie被删除。如果设置了过期时间,则浏览器会在cookie过期时间时,删除该cookie。

cookie编码

通常我们都会对cookie的键值分别进行URL编码,但这在规范中没有规定必须这样。原始规范中明确必须编码的有逗号,分号和等号。

cookie安全

secure

可以在js中使用如下方式为cookie设置secure属性

document.cookie = "name=xxx;secure";

需要注意的是只有在https域名下才能使用js设置该属性。

当cookie拥有该属性时,cookie会以安全的方式与服务器通信,即只有在https连接中,才能被传入服务器进行会话验证。http连接则不会传递该信息。

httpOnly

该属性表示只有通过http或https请求才能够设置cookie,
任何通过其他方式调用cookie api的(如使用js获取)都将被浏览器忽略。

在浏览器中也无法使用js来设置httpOnly属性

localStorage和sessionStorage

localStoragesessionStorage是一种web存储技术称为 web stroage。与cookie相比,它们不会与服务器通信,同时它们的容量更大最少5M。

localStoragesessionStorage实现了Storage接口。localStorage没有过期时间,只要不删除就一直存在。sessionStorage的生命周期是会话期间(即浏览器tab打开期间)。它们拥有相同的方法和属性

  • length: 属性,用来获取存储的长度
  • key: 函数,获取第n个存储条目的键值
  • setItem: 函数,用来设置存储条目使用,由于所有存储值都会被转为字符串,所以对象存储需要先进行JSON
  • getItem: 函数,获取指定键值的存储条目,条目不存在返回null
  • removeItem: 函数,移除指定键值的存储条目
  • clear: 函数,清除所有条目

其他存储方式

如果有更大的数据需要存储,webstroage和cookie都无法满足,这时候就需要用到IndexDBWeb SQL,由于这两种存储较为复杂,并且不常用,这里不再做介绍。

@xwchris xwchris changed the title 技术小记-前端存储技术 前端存储技术 Oct 12, 2019
@xwchris xwchris closed this as completed Sep 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant