Interview question update - what is local storage?

insert image description here


what is local storage

Local storage refers to saving data on the user's local device for subsequent use and access. With local storage, web pages and applications can retain previously saved data even after the user closes the browser or reopens the page.

Common local storage methods include:

Cookies (Cookie): A cookie is a small piece of text information that is sent by the server to the browser and stored on the user's computer. They are often used to track and identify users, and store small amounts of data. Cookies can be set to expire and remain valid until expired. However, every HTTP request will send the cookie to the server, which may affect performance.

Web Storage (Web Storage): Web Storage provides two objects for saving data in the browser: localStorage and sessionStorage. These objects allow developers to store string data as key-value pairs. Unlike cookies, Web Storage data is stored on the client rather than transmitted to the server in each HTTP request. Among them, the data in localStorage has no expiration time and will be kept unless it is manually cleared; while the data in sessionStorage is only valid in the current session (invalid after closing the tab or browser).

IndexedDB (Indexed Database): IndexedDB is a built-in browser database that allows you to store and retrieve large amounts of structured data in the browser. It provides an asynchronous API for high-performance data operations and supports functions such as transactions and indexes.

Cache Storage: Cache storage is a cache area used to store downloaded resources, including HTML, CSS, JavaScript files, images, etc. It provides offline accessibility and speeds up page loading.

It should be noted that since the local storage is performed on the user device, the amount of stored data is limited, usually between a few megabytes and hundreds of megabytes. When using local storage, data security and privacy protection should be considered to avoid storing sensitive information.

In web development, according to specific needs and browser compatibility, you can choose an appropriate local storage method to save and retrieve data.

Cookies

A cookie is a small text file transferred between a browser and a server to store user session data for a particular website. It is sent by the server to the browser via the "Set-Cookie" header in the HTTP response header, and returned to the server via the "Cookie" header in subsequent requests.

The following is a detailed description of cookies:

  1. Data storage and format: Cookies store data in the form of key-value pairs (key-value), and each cookie has a name and a corresponding value. For example, a cookie named "username" might have the value "JohnDoe". Each cookie can also contain other attributes, such as expiration time, domain name, path, and security flags.

  2. Cross-domain restrictions: Cookies are restricted by the same-origin policy. This means that a cookie can only be set and accessed by the domain that created it. Pages under different domain names cannot directly access the cookies set by each other. However, the way to share cookies across domains can be achieved through server-side settings, such as setting the Access-Control-Allow-Origin header to the domain name that is allowed to access.

  3. Optional attributes: A cookie can also set some optional attributes to control its behavior:

  4. Expiration time (Expires or Max-Age): Specifies the validity period of the cookie, which can be a date/time representation or the number of seconds relative to the current time.
    Domain: Specify which domain names can access cookies.
    Path (Path): Specify the pages under which paths can access cookies.
    Secure flag (Secure): If set to true, cookies can only be transmitted over secure HTTPS connections.
    HTTP Only flag (HttpOnly): If set to true, the cookie cannot be accessed by JavaScript code, which helps prevent cross-site scripting attacks.
    Usage scenarios: Cookies are usually used in the following aspects:

  5. Session management: By storing the user's session identifier (session ID), the server can identify and track the session state of a specific user in subsequent requests.
    User Preferences: Websites may use cookies to save users.

How to use Cookies in js

In JavaScript, you can use the document.cookie object to manipulate and manage cookies.

  1. Set cookies:

To set a cookie, you can assign a string to document.cookie. The format of the string is key=value;, and multiple key-value pairs can be added, separated by semicolons. For example:

document.cookie = "username=John Doe;";
document.cookie = "[email protected];";

Note: When setting a cookie, both the key name and the key value need to be URL-encoded. Special characters can be encoded using the encodeURIComponent() function.

  1. Get cookies:

All cookies saved in the browser can be obtained by reading the document.cookie property. The returned value is a semicolon-separated string containing key-value pairs for all cookies. For example:

var allCookies = document.cookie;
console.log(allCookies);

You can also write a custom function to get the specified cookie value. For example:

function getCookie(name) {
    
    
  var cookies = document.cookie.split("; ");
  for (var i = 0; i < cookies.length; i++) {
    
    
    var cookie = cookies[i].split("=");
    if (cookie[0] === name) {
    
    
      return decodeURIComponent(cookie[1]);
    }
  }
  return "";
}

var username = getCookie("username");
console.log(username);
  1. Delete cookies:

To delete a cookie, it can be set to a point in the past by setting an expiration time. For example:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
//注意:删除Cookie时,必须提供与设置Cookie时相同的路径和域。

In addition to setting, obtaining, and deleting cookies, you can also perform more precise control by specifying attributes such as cookie expiration time, path, and domain. For example:

document.cookie = "username=John Doe; expires=Fri, 31 Dec 2023 23:59:59 UTC; path=/; domain=example.com; secure";

In the above example, a cookie named username is set, it will exist until the end of 2023, the path is the root directory, the domain is example.com, and it can only be transmitted over a secure connection (HTTPS).

It should be noted that accessing and manipulating cookies is restricted by the same-origin policy. Cookies can only be read and set under the current domain, and cookie information of other domains cannot be accessed across domains.

localStorage

localStorage is a client-side storage mechanism provided by HTML5 for long-term storage of data in the browser. It allows developers to store key-value pair data in the user's local browser, and the data persists after the page is refreshed or closed.

Compared with traditional cookies, localStorage has the following characteristics:

  1. Larger capacity: The capacity of localStorage is usually larger than that of Cookie, which can store more data.
    Will not be sent to the server: The data stored in localStorage will not be automatically sent to the server in each request, reducing the burden of network transmission.
  2. Operate under the same-origin policy: localStorage follows the same-origin policy, and can only read and write under the same domain name, protocol, and port.
  3. Only store string type data: localStorage can only store string type data. If you need to store other data types, you can use JSON.stringify() to convert it to a string for storage, and then use JSON.parse() to read and parse it.

How to use localStorage in js

Using localStorage is very simple:

Storing data:

localStorage.setItem('key', 'value');

retrieve data:

var value = localStorage.getItem('key');

delete data:

localStorage.removeItem('key');

Clear all data:

localStorage.clear();

It should be noted that the data stored in localStorage is persistent, even if the user closes the browser or restarts the computer, the stored data still exists. Therefore, it is suitable for long-term storage of user preferences, local cache and other data. However, since it is stored locally, care needs to be taken to protect user privacy and data security, and avoid storing sensitive information or using localStorage for malicious purposes.

sessionStorage

sessionStorage is a client-side storage mechanism provided by HTML5 for temporarily saving data in the browser. Similar to localStorage, sessionStorage also allows developers to store key-value pair data in the user's local browser, but unlike localStorage, the data in sessionStorage is only valid during the current session (session).

A session period refers to the period of time between a user opening a page in a browser and closing the page. When the user closes the browser tab or the entire browser, the data in sessionStorage will be cleared.

How to use sessionStorage in js

The usage of sessionStorage is similar to that of localStorage:

Storing data:

sessionStorage.setItem('key', 'value');

retrieve data:

var value = sessionStorage.getItem('key');

delete data:

sessionStorage.removeItem('key');

Clear all data:

sessionStorage.clear();

Same as localStorage, sessionStorage can only store string type data, you can use JSON.stringify() and JSON.parse() to convert and parse other data types.

It should be noted that the data in sessionStorage is only shared within the same browser window or tab. If you open a webpage in a new window or tab, sessionStorage will be brand new and empty, and you cannot access the data stored in the previous window or tab.

sessionStorage is suitable for one-time, temporary data storage, such as passing data between form pages or saving user operation status during a session. It provides an easy and convenient way to handle temporary data needs without long-term consumption of user storage space.

Guess you like

Origin blog.csdn.net/weixin_48998573/article/details/131700636