Home > Web Front-end > JS Tutorial > Javascript local storage summary

Javascript local storage summary

高洛峰
Release: 2016-11-17 10:48:25
Original
1033 people have browsed it

1. Simple comparison of various storage solutions

Cookies: supported by all browsers, capacity is 4KB

UserData: only supported by IE, capacity is 64KB

Flash: 100KB, non-HTML native, requires plug-in support

Google Gears SQLite: requires plug-in support, unlimited capacity

LocalStorage: HTML5, capacity is 5M

SesstionStorage: HTML5, capacity is 5M

globalStorage: unique to Firefox, Firefox13 no longer supports this method

UserData is only supported by IE , Google Gears SQLite requires plug-ins, and Flash has gradually withdrawn from the stage of history with the emergence of HTML5, so today our protagonists are only three of them: Cookie, LocalStorge, SessionStorge;

2. Cookie

As a front-end that deals with Cookies The number of times will definitely not be less. Cookie is a relatively old technology. In 1993, Netscape employee Lou Montulli invented today's widely used cookies in order to further improve the access speed when users visit a website, and at the same time to further realize a personalized network. Cookies used.

2.1 Characteristics of Cookies

Let’s first look at the characteristics of Cookies:

1) The size of cookies is limited. The cookie size is limited to 4KB and cannot accept big data like large files or emails.

2) As long as there is a request involving cookies, cookies will be sent back and forth between the server and the browser (this explains why local files cannot test cookies). Moreover, the cookie data is always carried in the http request from the same origin (even if it is not needed), which is also an important reason why the cookie cannot be too large. Orthodox cookie distribution is achieved by extending the HTTP protocol. The server adds a special line of instructions to the HTTP response header to prompt the browser to generate the corresponding cookie according to the instructions.

3) Every time a user requests server data, cookies will be sent to the server along with these requests. Server scripting languages ​​such as PHP can process the data sent by cookies, which can be said to be very convenient. Of course, the front end can also generate cookies. Using js to operate cookies is quite cumbersome. The browser only provides an object such as document.cookie, and assigning and obtaining cookies is more troublesome. In PHP, we can set cookies through setcookie() and obtain cookies through the super-global array $_COOKIE.

The content of cookie mainly includes: name, value, expiration time, path and domain. The path and domain together form the scope of the cookie. If the expiration time is not set, it means that the lifetime of this cookie is during the browser session. When the browser window is closed, the cookie disappears. This type of cookie that lasts for the duration of the browser session is called a session cookie. Session cookies are generally not stored on the hard disk but in memory. Of course, this behavior is not specified by the specification. If an expiration time is set, the browser will save the cookies to the hard disk. If you close and open the browser again, these cookies will still be valid until the set expiration time is exceeded. Cookies stored on the hard drive can be shared between different browser processes, such as two IE windows. Different browsers have different ways of handling cookies stored in memory.

2.2 Session

When it comes to Cookie, we can’t help but talk about Session.

Session mechanism. The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or may use a hash table) to save information. When the program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier (called session id). If it does, it means that a session has been created for this client before. , the server will retrieve the session according to the session id and use it (if it cannot be retrieved, a new one will be created). If the client request does not contain the session id, a session will be created for the client and a session id associated with this session will be generated. , the value of the session id should be a string that is neither repeated nor easy to find patterns to imitate. This session id will be returned to the client in this response for storage. The method of saving this session ID can use cookies, so that during the interaction process, the browser can automatically send this identification to the server according to the rules. Generally, the name of this cookie is similar to SEEESIONID. But cookies can be artificially disabled, and there must be other mechanisms to still pass the session id back to the server when cookies are disabled. A frequently used technique is called URL rewriting, which appends the session id directly to the end of the URL path. For example: http://damonare.cn?sessionid=123456 There is also a technology called form hidden fields. That is, the server will automatically modify the form and add a hidden field so that the session id can be passed back to the server when the form is submitted. For example:

<form name="testform" action="/xxx">
    <input type="hidden" name="sessionid" value="123456">
    <input type="text">
</form>
Copy after login

In fact, this technique can be simply replaced by applying URL rewriting to the action.

2.3 Cookie和Session简单对比

Cookie和Session 的区别:

1)cookie数据存放在客户的浏览器上,session数据放在服务器上。

2)cookie不是很安全,别人可以分析存放在本地的cookie并进行cookie欺骗,考虑到安全应当使用session。

3)session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能考虑到减轻服务器性能方面,应当使用cookie。

4)单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。

5)所以建议:

将登陆信息等重要信息存放为SESSION

其他信息如果需要保留,可以放在cookie中

2.4 document.cookie的属性

expires属性

指定了coolie的生存期,默认情况下coolie是暂时存在的,他们存储的值只在浏览器会话期间存在,当用户推出浏览器后这些值也会丢失,如果想让cookie存在一段时间,就要为expires属性设置为未来的一个过期日期。现在已经被max-age属性所取代,max-age用秒来设置cookie的生存期。

path属性

它指定与cookie关联在一起的网页。在默认的情况下cookie会与创建它的网页,该网页处于同一目录下的网页以及与这个网页所在目录下的子目录下的网页关联。

domain属性

domain属性可以使多个web服务器共享cookie。domain属性的默认值是创建cookie的网页所在服务器的主机名。不能将一个cookie的域设置成服务器所在的域之外的域。例如让位于order.damonare.cn的服务器能够读取catalog.damonare.cn设置的cookie值。如果catalog.damonare.cn的页面创建的cookie把自己的path属性设置为“/”,把domain属性设置成“.damonare.cn”,那么所有位于catalog.damonare.cn的网页和所有位于orlders.damonare.cn的网页,以及位于damonare.cn域的其他服务器上的网页都可以访问这个cookie。

secure属性

它是一个布尔值,指定在网络上如何传输cookie,默认是不安全的,通过一个普通的http连接传输

2.5 cookie实战

这里我们使用javascript来写一段cookie,借用w3cschool的demo:

function getCookie(c_name){
    if (document.cookie.length>0){
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1){
            c_start=c_start + c_name.length+1
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return "";
}

function setCookie(c_name,value,expiredays){
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+
            ((expiredays==null) ? "" : "; expires="+exdate.toUTCString())
}
function checkCookie(){
    username=getCookie(&#39;username&#39;)
    if(username!=null && username!=""){alert(&#39;Welcome again &#39;+username+&#39;!&#39;)}
    else{
        username=prompt(&#39;Please enter your name:&#39;,"")
        if (username!=null && username!=""){
            setCookie(&#39;username&#39;,username,355)
        }
    }
}
Copy after login

注意这里对Cookie的生存期进行了定义,也就是355天

3. localStorage

这是一种持久化的存储方式,也就是说如果不手动清除,数据就永远不会过期。

它也是采用Key - Value的方式存储数据,底层数据接口是sqlite,按域名将数据分别保存到对应数据库文件里。它能保存更大的数据(IE8上是10MB,Chrome是5MB),同时保存的数据不会再发送给服务器,避免带宽浪费。

3.1 localStorage的属性方法

下表是localStorge的一些属性和方法

Javascript local storage summary

3.2 localStorage的缺点

① localStorage大小限制在500万字符左右,各个浏览器不一致

② localStorage在隐私模式下不可读取

③ localStorage本质是在读写文件,数据多的话会比较卡(firefox会一次性将数据导入内存,想想就觉得吓人啊)

④ localStorage不能被爬虫爬取,不要用它完全取代URL传参

4. sessionStorage

和服务器端使用的session类似,是一种会话级别的缓存,关闭浏览器会数据会被清除。不过有点特别的是它的作用域是窗口级别的,也就是说不同窗口间的sessionStorage数据不能共享的。使用方法(和localStorage完全相同):

Javascript local storage summary

5. sessionStorage和localStorage的区别

sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。当用户关闭浏览器窗口后,数据立马会被删除。

localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。第二天、第二周或下一年之后,数据依然可用。

5.1 测试

sessionStorage:

if (sessionStorage.pagecount){
    sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}else{
      sessionStorage.pagecount=1;
}
console.log("Visits "+ sessionStorage.pagecount + " time(s).");
Copy after login

测试过程:我们在控制台输入上述代码查看打印结果

控制台首次输入代码:

Javascript local storage summary

关闭窗口,控制台再次输入代码:

Javascript local storage summary

所谓的关闭窗口即销毁,就是这样,关闭窗口重新打开输入代码输出结果还是上面图片的样子,也就是说关闭窗口后sessionStorage.pagecount即被销毁,除非重心创建。或者从历史记录进入才会相关数据才会存在。好的,我们再来看下localStorge表现:

if (localStorage.pagecount){
    localStorage.pagecount=Number(localStorage.pagecount) +1;
}else{
    localStorage.pagecount=1;
 }
console.log("Visits "+ localStorage.pagecount + " time(s).");
Copy after login

控制台首次输入代码:

Javascript local storage summary

关闭窗口,控制台再次输入代码:

Javascript local storage summary

6. web Storage和cookie的区别

Web Storage(localStorage和sessionStorage)的概念和cookie相似,区别是它是为了更大容量存储设计的。Cookie的大小是受限的,并且每次你请求一个新的页面的时候Cookie都会被发送过去,这样无形中浪费了带宽,另外cookie还需要指定作用域,不可以跨域调用。

除此之外,Web Storage拥有setItem,getItem,removeItem,clear等方法,不像cookie需要前端开发者自己封装setCookie,getCookie。

但是Cookie也是不可以或缺的:Cookie的作用是与服务器进行交互,作为HTTP规范的一部分而存在 ,而Web Storage仅仅是为了在本地“存储”数据而生





Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template