This is a common interview question these days. Write a blog to summarize it.
introduce
Cookie
preface
One of the biggest problems in the early days of the web was managing state. In short, the server has no way of knowing whether two requests are coming from the same browser. The easiest way back then was to insert some parameters into the page at request time and pass them back on the next request. This requires using a hidden form with parameters, or passing it as part of the URL parameters. Both solutions are manual and error-prone. Cookies come in to solve this problem.
role
Cookies are plain text and have no executable code. Store data. When users visit a website (webpage), we can store data on visitors’ computers through cookies, or the data (usually encrypted) stored on users’ local terminals by some websites for identifying users’ identities and session tracking.
How to work
When a web page sends an HTTP request, the browser checks whether there is a cookie and automatically adds it to the cookie field in the Request header. This is what the browser does automatically for us, and it does it for us every time we make an HTTP request. This feature is important because it relates to what kind of data is appropriate to store in cookies.
The data stored in cookies will be automatically placed in HTTP requests by the browser every time. If these data are not sent to the server in every request, the automatic processing of the browser will undoubtedly increase the network overhead. However, if the data is the data that needs to be sent to the server on each request (such as authentication information), the browser’s automatic processing of this setting greatly reduces the need to add data repeatedly. Therefore, cookies are especially suitable for setting “information to be carried on every request (most typically authentication information)”, while other types of data are not suitable.
Characteristics of the
- Different browsers store cookies in different locations and cannot be used universally.
- Cookie storage is distinguished in the form of domain names. Cookies stored in different domains are independent.
- We can set the domain in which the cookie takes effect (the subdomain of the domain in which the cookie is currently set), that is, the cookies we can operate on are the current domain and all subdomains under the current domain
- The number of cookies that can be stored in a domain name is limited. The number of cookies that can be stored in a domain name varies with different browsers. Generally, the number is 20.
- There is also a limit on the size of each cookie. Different browsers store different cookie sizes, generally 4KB.
- Cookies can also be set to expire at the end of the session by default, and will be automatically destroyed when the time expires
Cookie values can be set and read.
Set up the
Client Setup
Document. cookie = 'name = value '; document.cookie = 'username=cfangxu; Domain=baike.baidu.com 'and set the valid domainCopy the code
Note: Clients can set the following cookie options: Expires, Domain, PATH, secure (conditional: secure cookies can only be set in HTTPS web pages), but cannot set the HttpOnly option.
Server side Settings
Whether you request a resource file (such as HTML/JS/CSS/image) or send an Ajax request, the server returns a response. In response header, there is an item called set-cookie, which is specially used by the server to set cookies.
The set-cookie header is a string of the following format (the part in parentheses is optional) : set-cookie: value[; Expires =date][; domain=domain][; path=path][; Secure]Copy the code
Note: only one set-cookie field can be set. If you want to set multiple cookies, you need to add the same number of set-cookie fields. The server can Set all the options for the cookie: Expires, Domain, PATH, Secure, HttpOnly The options specified by set-cookie are only used on the browser side and are not sent to the server side.
read
Cookie is a string value that contains all cookies from the current web site (to avoid cross-domain scripting (XSS) attacks, this method can only fetch non-HTTPOnly cookies). It concatenates all cookies with a semicolon + space, for example username=chenfangxu; job=coding
Modify the cookie
To modify a cookie, you simply reassign and the old value is overwritten by the new value. Note, however, that when setting new cookies, the path/domain options must remain the same as the old cookie. Otherwise, the old value is not modified, but a new cookie is added.
delete
Set the expiration time of the cookie to the past time. The path/domain/ options must remain the same as the old cookie.
Pay attention to
If only one value is set, then the value in the cookie is counted; If two cookies are set with the same key value, the one below overwrites the one above.
Properties of cookie (optional)
Expiration time
If we want to store a cookie for a long time. The cookie needs to be set to expire at the same time. If not set, cookies are stored temporarily by default and destroyed automatically when the browser closes the process
Note: document.cookie = 'name = value; Expires =' + GMT date string;Copy the code
New Date().setDate(odate.getDate () + 5); 5 days more than the current time
An example of setting cookie timeliness
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.togmtString ())} setCookie('username','cfangxu',30)Copy the code
Expires is an option in HTTP /1.0. In the new HTTP /1.1 protocol, expires has been replaced by max-age, both of which limit how long a cookie can last. The expires value is a point in time (cookie expiration = expires), while the max-age value is a time period in seconds (cookie expiration = creation + max-age). In addition, the default value of max-age is -1(that is, the validity period is session); Max-age has three possible values: negative, 0, and positive. Negative: validity period session; 0: deletes cookies. Positive: The validity period is creation time + max-age
Domain concept for cookies (Domain option)
Domain specifies which domain or domains cookies will be sent to. By default, domain is set to the domain of the page that created the cookie, so the cookie is sent to the server when a request is made to the same domain.
The browser does a tail comparison (starting at the end of the string) between the value of the domain and the requested domain name, and sends matching cookies to the server.
Client Setup
document.cookie = “username=cfangxu; path=/; Domain=qq.com “as above: “www.qq.com” shares a related domain name “qq.com” with “sports.qq.com”. If we want the cookies under “sports.qq.com” to be accessed by “www.qq.com”, We need to use the domain property of the cookie, and we need to set the path property to “/”.
Server Settings
Set-Cookie: username=cfangxu; path=/; Note: The value of domain must be inter-domain access. You cannot set domain to a non-primary domain name.
Cookie path concept (Path option)
Cookies are generally created because the user visits the page, but not only on the page that created the cookie can access the cookie. For security reasons, by default, only web pages that are in the same directory or subdirectory as the page that created the cookie are accessible. That is, the path property can specify cookies for server-specific documents. The url set by this property and the URL path with this prefix are valid.
Client Setup
The most common example is to have cookies in the root directory, so that no matter which child page creates the cookie, all pages can access it.
document.cookie = "username=cfangxu; path=/"
Server Settings
Set-Cookie:name=cfangxu; path=/blog
The path option will match /blog, /blogrool, etc. Any option that begins with /blog is valid. Note that the path attribute is compared only after the Domain option is verified. The default value of the path attribute is the PATH part of the URL to which the set-cookie header is sent.
Domain and PATH summary:
Domain is the domain name and path is the path. Together, they form the URL. Domain and Path restrict which urls cookies can be accessed. So the domain and pathoptions together determine when the cookie is automatically added to the request header by the browser and sent out. If these two options are not set, the default values are used. The default value of domain is the domain name of the web page where the cookie is set, and the default value of path is the directory where the cookie is set.
Cookie security (Secure option)
Generally, cookie information is transmitted through HTTP connections, which is easy to be checked, so the information stored in cookies is easy to be stolen. If what is passed in the cookie is important, then encrypted data transfer is required.
The secure option is used to set cookies to be sent only on secure requests. Cookies with the Secure option can be sent to the server only when the request is HTTPS or other security protocol.
document.cookie = "username=cfangxu; secure"
If cookie is set to Secure, only data transmission between cookie and server is encrypted, but the local cookie file is not encrypted. Even if you set the secure property, it does not mean that others cannot see the cookies stored locally on your machine. Confidential and sensitive information should never be stored or transmitted in cookies because the entire mechanism of cookies is inherently insecure
Note: If you want to set secure cookies on the client side, i.e. the web page, through JS, you must ensure that the web page is HTTPS protocol. Cookies of the secure type cannot be set on HTTP web pages.
httpOnly
This option sets whether cookies can be accessed through JS. By default, cookies do not have the httpOnly option (i.e. empty), so by default, clients can access (including reading, modifying, deleting, etc.) this cookie through JS code. When the cookie has the httpOnly option, the client cannot access (including reading, modifying, deleting, etc.) the cookie through JS code.
HttpOnly cookies cannot be set by javascript on the client side. This type of cookie can only be set by the server side.
Cookie coding
Cookie is actually a string, but the string is treated as a special character. Therefore, when the key and value of cookies contain these three special characters, additional encoding is required. Escape is generally used for encoding, and unescape is used for decoding when reading cookies. Of course you can also use encodeURIComponent/decodeURIComponent or encodeURI/decodeURI, check the information about the coding
Third party cookies
Usually the cookie’s field matches the browser address’s field, which is called a first-party cookie. The third-party cookie is the cookie whose field does not match the field in the address bar. This kind of cookie is usually used in third-party advertising websites. In order to track the browsing history of users, and according to the collection of users’ browsing habits, push relevant advertisements to users. Questions about the safety of the third party cookies and cookie can view mp.weixin.qq.com/s/oOGIuJCpl…
-
Cookie Recommendation Resources
-
Talk about the cookie
-
HTTP cookies,
-
LocalStorage
HTML5 new approach, but compatible with IE8 and above.
The characteristics of
- Life cycle: Persistent local storage that never expires unless it is actively deleted.
- Stored information is shared within the same domain.
- When you add, modify, or delete localStorage on this page, this page will not trigger the storage event, but other pages will trigger the storage event.
- Size: said to be 5m-10m (different browser size)
- It can be opened locally in non-IE browsing. The Internet Explorer browser must be opened on the server.
- LocalStorage is essentially a string read. If you store too much content, memory space will be consumed and pages will become jammed
- LocalStorage is restricted by the same Origin policy
Set up the
localStorage.setItem('username','cfangxu');
To obtain
Localstorage.getitem (‘username’) can also get the key name localstorage.getitem (‘username’
delete
Localstorage.removeitem (‘username’) can also clear all storage localstorage.clear ()
Storage events
Triggered when the storage changes. The event callback function has a parameter event, which is a StorageEvent object and provides some useful properties, as shown in the following table:
Property | Type | Description |
---|---|---|
key | String | The named key that was added, removed, or moddified |
oldValue | Any | The previous value(now overwritten), or null if a new item was added |
newValue | Any | The new value, or null if an item was added |
url/uri | String | The page that called the method that triggered this change |
SessionStorage
In fact, similar to localStorage, also localStorage, session localStorage
Features:
Used to store data in a session locally, which can only be accessed by pages in the same session and is destroyed when the session ends. Therefore, sessionStorage is not a persistent local storage, only session level storage. This means that as long as the browser window is not closed, the data will still exist even if the page is refreshed or another page is entered. After closing the window, sessionStorage will be destroyed, or open another page of the same origin in a new window, sessionStorage is also not.
Session
What is Session? When is a Session created?
Session: In computers, especially in network applications, it is called “Session control”. The Session object stores properties and configuration information required for a specific user Session. This way, variables stored in the Session object will not be lost when the user jumps between Web pages of the application, but will persist throughout the user Session. When a user requests a Web page from an application, the Web server automatically creates a Session object if the user does not already have a Session. When a session expires or is abandoned, the server terminates the session.
Why use sessions?
Because many third parties can obtain this Cookie, the server cannot determine whether the Cookie is sent by a real user, so the Cookie can be forged to achieve login and some HTTP requests. If sessions are a little more secure than cookies, let’s start with the concept of SessionID. What is a SessionID? When the client requests the server for the first time, the server will create a Session for the client and calculate the ID of a Session through a special algorithm. The next time the client requests resources (the Session has not expired), the browser will place the sessionID(essentially cookies) in the request header. After receiving the request, the server gets the SessionID of the request. The server finds the session with this ID and returns it to the requester for use.
The lifetime of the Session?
According to the requirements, generally, half an hour. For example, if you log in to a server, the server returns a sessionID, and there are no HTTP requests to the server within half an hour after successful login. If you make an HTTP request after half an hour, you will be prompted to log in again.
What are the drawbacks of Session?
Because sessions are stored on the server, too many sessions may cause pressure on the server. In my opinion, the life cycle of a Session is a way to reduce the stress on the server.
The difference between
- LocalStorage will not automatically expire unless manually cleared by the user. Cookies are temporary storage by default and will be automatically destroyed when the browser closes the process. SessionStorage is local SessionStorage and data will be destroyed after the session ends.
- Cookie storage size is generally 4K and will be sent to the server, so it mainly stores what needs to be carried in each request, while LocalStorage storage size is generally 5-10M. LocalStorage is essentially a string read. If too much content is stored, the memory space will be consumed and the page will become jammed.
- Session is realized based on Cookie. The specific method is to store the SessionID in Cookie. Every time the server receives a request, it will find the corresponding Session according to the ID and return it to the requester. Cookie is a file stored in the browser, Session is a file stored in the server. Too many sessions will put pressure on the server, but the lifetime of a Session is usually half an hour, which is also a way to reduce the pressure on the server.
Other front-end storage methods
web SQL database
Let’s start with the ones that will be replaced. There are several reasons why they will be replaced:
- The W3C abandon
Web SQL database
In the draft, and by the end of 2010, the spec is no longer supported. Browser vendors already support it, and don’t plan to support it if they don’t, such as IE and Firefox. - Why do you want to leave? because
Web SQL database
Is essentially a relational database, back-end may be familiar with, but there are a lot of front-end is not familiar with, although the simple operation of SQL is not difficult, but also need to learn. - Once you are familiar with SQL, you have to convert things you want to store, such as objects, into SQL statements in real operation, which is also quite troublesome.
indexedDB
IndexedDB is a low-level API for clients to store large amounts of structured data (including files/blobs). The API uses indexes to enable a high-performance search of this data. While Web Storage is useful for storing smaller amounts of data, this approach is less useful for storing larger amounts of structured data. IndexedDB provides a solution.
So, the IndexedDB API is powerful, but may seem too complex for simple cases, so it depends on your business scenario to decide whether to use it or not.
IndexedDB is an object-oriented database based on JavaScript. IndexedDB allows you to store and retrieve objects indexed by key;
The basic patterns encouraged by IndexedDB are as follows:
- Open the database and start a transaction.
- Create an Object Store.
- Build a request to perform some database operation, such as adding or extracting data.
- Wait for the operation to complete by listening for DOM events of the correct type.
- Do something on the result of the operation (found in the Request object)
1. First open the indexedDB database
Syntax: window.indexeddb.open (dbName, version)
var db; Var request = window.indexeddb. open('myTestDatabase'); var request = window.indexeddb. open('myTestDatabase'); // Request. Onsuccess = function (event) {// Store the data result. db = request.result; } request.onerror = function (event) { alert("Why didn't you allow my web app to use IndexedDB? !" ); } // The database has been created for the first time, or the new version passed by window.indexeddb.open (higher than the current version) request.onupgradenneeded = function (event) {}Copy the code
Onupgradenneeded event: Updates the database’s schema, which creates or deletes object storage space, and will be called as part of a versionchange transaction that allows you to process object storage space. This versionchange transaction is created when the database is first opened or when the specified version number is higher than that of the currently persisted database. Onupgradenneeded is the only place where we can modify the database structure. Within this, we can create and delete object storage Spaces and build and delete indexes.
2. Build the database
IndexedDB uses object storage space instead of tables, and a single database can contain any amount of object storage space. Each time a value is stored in an object store, it is associated with a key.
// The database is created for the first time. Request. Onupgradeneneeded = function (event) {// Success has its own DB required by success. Var db = event.target.result; var db = event.target.result; Var objectStore = db.createObjectStore('testItem',{keyPath: 'id',autoIncrement: true}); CreateIndex ('id','id',{unique: objectStore.createIndex('id','id',{unique: true}) objectStore.createIndex('name','name'); objectStore.createIndex('age','age'); // Add ({name: 'cfangxu', age: '27'}); }Copy the code
Note: After executing, it is not visible in the debugger toolbar Application indexedDB, so you need to right click to refresh it.
Syntax for creating an index:
CreateIndex (indexName, keyPath, objectParameters) indexName: Indicates the name of the created index. An empty name can be used as the index. KeyPath: keyPath to use for the index. You can use empty keyPath or pass keyPath as an array. ObjectParameters: This parameter is optional. One of the common arguments is unique, indicating whether the value of the field is unique and cannot be repeated. For example, in this demo id cannot be repeated, so there is a setting:Copy the code
3. Add data
The above code builds the field and adds a bit of data, but the next step is needed if we want to operate outside the onupgradenneeded event. Since database operations are based on transactions, a transaction must be established before any operations can proceed, whether an edit is added or a database is deleted. Syntax: var transaction = db.transaction(dbName, “readwrite”); The first argument is a list of object storage Spaces that the transaction wants to span, either an array or a string. If you want the transaction to span all object storage space you can pass in an empty array. If you don’t specify anything for the second parameter, you get a read-only transaction. Because here we want to write so we need to pass in the “readwrite” flag.
var timer = setInterval(function () { if(db) { clearInterval(timer); Var transaction = db.transaction(['testItem'], 'readwrite'); Var objectStore = transaction.objectStore('testItem'); // Add data to objectStore.add({name: 'xiaoming', age: '12'}); objectStore.add({ name: 'xiaolong', age: '20' }); }}, 100).Copy the code
Why use an interval timer? Since this is a demo, it is normal to have an operation before writing to the database. In our demo, js will execute the transaction to the database faster than the onSuccess event callback of indexedDB, resulting in undefined db, so we wrote an interval timer to wait for it for a while.
4. Get data
var transaction = db.transaction(['testItem'], 'readwrite'); var objectStore = transaction.objectStore('testItem'); var getRquest = objectStore.get(1); getRquest.onsuccess = function (event) { console.log(getRquest.result); {name: "cfangxu", age: "27", id: 1}Copy the code
5. Modify data
var transaction = db.transaction(['testItem'], 'readwrite'); var objectStore = transaction.objectStore('testItem'); var getRquest = objectStore.put({ name: 'chenfangxu', age: '27', id:1 }); // Change the value of 1Copy the code
6. Delete data
var transaction = db.transaction(['testItem'], 'readwrite'); var objectStore = transaction.objectStore('testItem'); var getRquest = objectStore.delete(1); // delete data with id 1Copy the code
After executing the above example, be sure to right-click to refresh indexedDB; it will not change by itself.
- IndexedDB: indexedDB: indexedDB: indexedDB: indexedDB: indexedDB:
Reference article: very complete very complete front-end local storage explanation