search
HomeWeb Front-endJS TutorialJavascript local storage summary

Javascript local storage summary

Nov 22, 2016 am 11:01 AM
javascript

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)
        }
    }
}

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).");

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

控制台首次输入代码:

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).");

控制台首次输入代码:

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仅仅是为了在本地“存储”数据而生


Statement
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor