Home Backend Development PHP Tutorial What is the difference between sessionStorage and localStorage

What is the difference between sessionStorage and localStorage

Sep 07, 2017 am 09:38 AM
localstorage sessionstorage

The difference between sessionStorage and localStorage is: 1. localStorage has no expiration time; 2. sessionStorage stores data for a session, and the life cycle is the same as the session. When the user closes the browser, the data will be deleted.

What is the difference between sessionStorage and localStorage

The difference between sessionStorage and localStorage

As we all know, since the emergence of the HTML 5 standard, Localized storage once became a hotly searched keyword. At the beginning of HTML 5, there were two ways of local storage: one was web Storage and the other was web SQL. Since the implementation of web SQL is based on SQLite, it is more inclined to the direction of DataBase, and W3C officially announced in November 2011 that it would no longer maintain the web SQL specification, so its API interface currently does not fall within the scope of HTML 5. Therefore, the HTML 5 local storage we often talk about currently mostly refers to web Storage.

The following is a detailed description and explanation of WebStorage and its two forms.

1. webStorage

webStorage is an important function introduced by HTML5. It is often used in the process of front-end development. It can be used on the client Locally stored data is similar to cookies, but its function is much more powerful than cookies. The size of the cookie is only about 4Kb (different browsers have different sizes), while the size of webStorage is 5MB. The methods provided by its API are as follows:

setItem(key,value) - save data and store information in the form of key-value pairs.

getItem(key)——Get the data and pass in the key value to get the corresponding value.

removeItem(key)——Delete a single data and remove the corresponding information based on the key value.

clear()——Delete all data

key(index)——Get the key of an index

2, localStorage

The life cycle of localStorage is permanent. If you use localStorage to store data, even if you close the browser, the data will not disappear unless you actively delete the data. The method used is as shown above. localStorage has a length attribute, you can check how many records of data it has. The usage is as follows:

     var storage = null;
         if(window.localStorage){              //判断浏览器是否支持localStorage
            storage = window.localStorage;     
            storage.setItem("name", "Rick");    //调用setItem方法,存储数据
            alert(storage.getItem("name"));     //调用getItem方法,弹框显示 name 为 Rick
            storage.removeItem("name");     //调用removeItem方法,移除数据
            alert(storage.getItem("name"));   //调用getItem方法,弹框显示 name 为 null
 
         }
Copy after login

localStorage is simpler than sessionStorage, and there are not many things to pay attention to.

3. sessionStorage

The life cycle of sessionStorage is before the browser is closed. In other words, the data will always exist until the entire browser is closed. sessionStorage also has a length attribute, and its basic judgment and usage are the same as those of localStorage. The following points need to be noted:

<1> Refreshing the page will not eliminate the data

For verification, I prepared two html files, one is index .html and the other is text.html. As for text.html, its origin will be discussed in detail later. The html codes of the two are as follows:

index.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Test</title>
        <script>
            function submit() {
                var str = document.getElementById("text").value.trim();
                setInfo(str);
                document.getElementById("text").value = "";
            }
            //储存数据
            function setInfo(name) {
                var storage = window.sessionStorage;
                storage.setItem(&#39;name&#39;, name);
            }
            //显示数据
            function shows() {
               var storage = window.sessionStorage;
               var str = "your name is " + storage.getItem("name");
               document.getElementById("text").value = str;
            }
         </script>
    </head>
    <body>
         <input type="button" value="Login" οnclick="submit()" />
         <input type="text" name="text" id="text" />
         <input type="button" value="show" οnclick="shows()" />
         <a href="text.html" target="_blank">点击打开</a>
    </body>
    </html>
Copy after login

The text.html page is as follows:

     <!DOCTYPE html>
     <html>
     <head>
         <meta charset="UTF-8">
         <title>Title</title>
     </head>
     <body>
         <script>
             var storage = window.sessionStorage;
             alert(storage.getItem("name"));
         </script>
     </body>
     </html>
Copy after login

The result of opening the index.html page is as follows:

What is the difference between sessionStorage and localStorage

When the show button is clicked, "your name is null" is displayed in the input box. At this time, there is no data with the key value "name" stored in sessionStorage. After entering "Rick" in the text, click the login button. When the input box is cleared, the data has been stored in sessionStorage. Then click the show button, and "your name is Rick" will be displayed. At this time, click the browser to refresh the web page, and then click the show button. The input box still displays "your name is Rick"

Only links opened on the current page can be used. Access sessionStorage data;

Remember the text.html page you prepared? It is now its turn to play its role. In order to verify, we follow the above steps and open text.html. The result is as follows:

What is the difference between sessionStorage and localStorage

As you can see, this value is null and the value of "name" cannot be obtained. Now, close this text.html page and open the link by clicking on the index.html page. You can see the following results:

What is the difference between sessionStorage and localStorage

Therefore, you can know that at the current time The link opened on the page can access the data in sessionStorage. Later, after some other tests, I found that after opening the text.html page from index.html, closing index.html and refreshing text.html, the data in sessionStorage can also be accessed. The data in sessionStorage can only be eliminated when index.html and all pages opened from it are closed or the browser is closed directly.

Using window.open to open the page and changing the localtion.href method can obtain the data inside sessionStorage

The above two methods have been tested. And indeed it is. Interested students can actually test the results. I will not summarize the differences between localStorage and sessionStorage.

In short, when using it, pay attention to the points mentioned above, and you can avoid many unnecessary pitfalls when using it.

For more related knowledge, please visit PHP Chinese website! !

The above is the detailed content of What is the difference between sessionStorage and localStorage. For more information, please follow other related articles on the PHP Chinese website!

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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
Why can't localstorage successfully save data? Why can't localstorage successfully save data? Jan 03, 2024 pm 01:41 PM

Why does storing data to localstorage always fail? Need specific code examples In front-end development, we often need to store data on the browser side to improve user experience and facilitate subsequent data access. Localstorage is a technology provided by HTML5 for client-side data storage. It provides a simple way to store data and maintain data persistence after the page is refreshed or closed. However, when we use localstorage for data storage, sometimes

How to set the expiration time of localstorage items How to set the expiration time of localstorage items Jan 11, 2024 am 09:06 AM

How to set the expiration time of localstorage requires specific code examples. With the rapid development of the Internet, front-end development often requires saving data in the browser. Localstorage is a commonly used WebAPI that aims to provide a way to store data locally in the browser. However, localstorage does not provide a direct way to set the expiration time. This article will introduce how to set the expiration time of localstorage through code examples.

What are the methods to recover deleted Localstorage data? What are the methods to recover deleted Localstorage data? Jan 11, 2024 pm 12:02 PM

How to recover deleted Localstorage data? Localstorage is a technology used to store data in web pages. It is widely used in various web applications to share data between multiple pages. However, sometimes we may accidentally delete data in Localstorage, which causes us trouble. So, how to recover deleted Localstorage data? Below are specific steps and code examples. Step 1: Stop writing to Loca

Why is localstorage unsafe? Why is localstorage unsafe? Oct 10, 2023 pm 05:38 PM

The reasons why localstorage is unsafe are unencrypted data, XSS attacks, CERF attacks, capacity limitations, etc. Detailed introduction: 1. Data is not encrypted. Localstorage is a simple key-value pair storage system. It stores data in the user's browser in clear text, which means that anyone can easily access and read the data stored in localstorage. If sensitive information is stored in localstorage, hackers or malicious users can easily obtain this information and so on.

Steps and precautions for using localstorage to store data Steps and precautions for using localstorage to store data Jan 11, 2024 pm 04:51 PM

Steps and precautions for using localStorage to store data This article mainly introduces how to use localStorage to store data and provides relevant code examples. LocalStorage is a way of storing data in the browser that keeps the data local to the user's computer without going through a server. The following are the steps and things to pay attention to when using localStorage to store data. Step 1: Check whether the browser supports LocalStorage

Why can't local storage save data correctly? Why can't local storage save data correctly? Jan 03, 2024 pm 01:41 PM

Why can't localstorage save my data normally? In web development, we often need to save the user's data locally so that the data can be quickly loaded or restored the next time the user visits the website. In the browser, we can use localStorage to achieve this function. However, sometimes we find that data saved using localStorage does not work properly. So why does this happen? In understanding why localStorage

Why does localstorage fail so quickly? Why does localstorage fail so quickly? Dec 14, 2023 pm 02:55 PM

Reasons why localstorage fails quickly: 1. Browser support; 2. Storage space limit; 3. Security policy; 4. Page refresh and close; 5. JavaScript error. Detailed introduction: 1. Browser support. Different browsers may have different levels of support for LocalStorage. Some older browsers may not support LocalStorage, or there may be flaws in the implementation of LocalStorage, resulting in data failure; 2. Storage space limitations, etc. wait.

what is localstorage what is localstorage Dec 19, 2023 pm 02:07 PM

localStorage is a web API that can store and retrieve data in a web browser. It allows websites to store data in the user's local browser instead of on the server. It can be used to store many different types of data, such as user settings, preferences, shopping cart data, etc. There are different storage limits in different browsers, and there is usually a maximum storage limit. It can be used to improve the user experience of the website and provide personalized services. But you need to pay attention to privacy and so on when using localStorage.

See all articles