Home > Web Front-end > JS Tutorial > body text

Javascript local storage summary

高洛峰
Release: 2016-11-22 11:01:06
Original
1187 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 processing methods for cookies stored in memory.

2.2 Session

When it comes to cookies, 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>

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

2.3 Simple comparison of Cookie and Session

The difference between Cookie and Session:

1) Cookie data is stored on the customer's browser, and session data is placed on the server.

2) Cookies are not very secure. Others can analyze cookies stored locally and conduct cookie spoofing. Sessions should be used for security reasons.

3) The session will be saved on the server for a certain period of time. When visits increase, it will take up more of your server's performance. In order to reduce server performance, cookies should be used.

4) The data saved by a single cookie cannot exceed 4K, and many browsers limit a site to save up to 20 cookies.

5) So it is recommended:

Save important information such as login information as SESSION

If other information needs to be retained, it can be placed in cookies

2.4 document.cookie attributes

expires attribute

specifies the survival of the coolie By default, cookies are temporary. The values ​​they store only exist during the browser session. These values ​​will be lost when the user exits the browser. If you want the cookie to exist for a period of time, set the expires attribute to An expiration date in the future. This has now been replaced by the max-age attribute, which sets the cookie's lifetime in seconds.

path attribute

It specifies the web page associated with the cookie. By default, a cookie is associated with the web page that creates it, web pages in the same directory as the web page, and web pages in subdirectories of the directory where this web page is located.

domain attribute

domain attribute allows multiple web servers to share cookies. The default value of the domain attribute is the host name of the server where the web page that created the cookie is located. The domain of a cookie cannot be set to a domain other than the domain where the server is located. For example, let the server located at order.damonare.cn be able to read the cookie value set by catalog.damonare.cn. If the cookie created by the catalog.damonare.cn page sets its path attribute to "/" and the domain attribute to ".damonare.cn", then all web pages located at catalog.damonare.cn and all pages located at orlders.damonare .cn web pages, as well as web pages on other servers located in the damonare.cn domain, can access this cookie.

secure attribute

It is a Boolean value that specifies how to transmit cookies on the network. It is insecure by default and is transmitted through an ordinary http connection

2.5 Cookie practice

Here we use javascript to write a cookie, borrowed w3cschool's 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

Note that the lifetime of the cookie is defined here, which is 355 days

3. localStorage

This is a persistent storage method, which means that if it is not cleared manually, the data will be forever Will not expire.

It also uses the Key-Value method to store data. The underlying data interface is sqlite, and the data is saved to the corresponding database file according to the domain name. It can save larger data (10MB on IE8, 5MB on Chrome), and the saved data will not be sent to the server to avoid wasting bandwidth.

3.1 Attribute methods of localStorage

The following table is some attributes and methods of localStorage

Javascript local storage summary

3.2 Disadvantages of localStorage

① The size of localStorage is limited to about 5 million characters, and each browser is inconsistent

② localStorage is in privacy mode It is not readable

③ The essence of localStorage is to read and write files. If there is a lot of data, it will be stuck (firefox will import the data into the memory at one time, which is scary when you think about it)

④ localStorage cannot be crawled by crawlers, do not use it It completely replaces URL parameter passing

4. sessionStorage

is similar to the session used on the server side. It is a session-level cache. When the browser is closed, the data will be cleared. But something special is that its scope is at the window level, which means that sessionStorage data cannot be shared between different windows. Usage method (exactly the same as 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!