❝
With the advent of Web applications came the need to store user information directly on the client side. So what are the common storage methods on the front end?
❞
preface
If this article is helpful to you, ❤️ follow + like ❤️ to encourage the author, the article public account first launch, pay attention to “front-end South Jiu” the first time to get the latest article ~
HTML5 common storage methods
- Local storage:
localStorage
.sessionStorage
.cookies
- Offline cache:
application cache
- Front-end database:
indexedDB
.webSQL
cookie
❝
HTTP cookies, also known as cookies, were originally used to store session information on the client side. “A cookie is bound to a specific domain name, and when it is set, it is sent along with the request to the domain where it was created.” This restriction ensures that the information stored in the cookie is only available to approved recipients and not accessed by other domains.
❞
The composition of the cookie
- Name: The name that uniquely identifies the cookie. Cookies are case insensitive and the cookie name must be URL-encoded.
- Value: The string value stored in the cookie, which must be URL-encoded.
- “Domain:” the valid domain of the cookie, to which all requests will contain the corresponding cookie.
- The cookie is sent to the server only if the “path:” request URL contains this path.
- Expiration Time: indicates when the cookie timestamp is deleted. (i.e., after what time it will not be sent to the server)
- When “Security Identifier:” is set, cookies will only be sent to the server if an SSL secure connection is being used.
limit
“Because the cookie is stored on the client machine, browsers impose restrictions to ensure it can’t be exploited maliciously.”
- No more than 300 cookies
- Each cookie does not exceed 4096 bytes (4KB)
- There are no more than 20 cookies per field
- Each field does not exceed 81920 bytes
In JavaScript cookie
Handling cookies in JavaScript is cumbersome because the interface is too simple, with only the document.cookie attribute of ** “BOM” **.
To get a cookie
Document. cookie Returns a string containing all valid cookies on the page, separated by semicolons;
name1=value1; name2=valve2; name3=value3Copy the code
“All names and values are URL-encoded and therefore must be useddecodeURIComponent()
Decoding”
Set the cookie
name=value; expires=expiration_time; path=domain_path; Domain =domain_namel secure // Among all these parameters, Only cookie name and value are required document.cookie = '${encodeURIComponent('name')}=${encodeURIComponent(' Nanjiu ')}; domain=bettersong.github.io; `Copy the code
Delete the cookie
“There is no direct way to delete existing cookies, but you can delete them by setting their expiration time.”
document.cookie = 'uid=dkfywqkrhkwehf23; expires=' + new Date(0) + '; path=/; secure;Copy the code
How do cookies work?
“The request:”
When the browser initiates a Request, it automatically checks for a cookie and adds the cookie to the Cookie field of the Request Headers
“The response:”
If the server requires a cookie, add a set-cookie field to the Response Headers field of an HTTP request. After receiving the cookie, the browser automatically parses and recognizes it and plants the cookie.
LocalStorage and sessionStorage
❝
The sessionStorage object only stores session data, which means data will only be stored until the browser closes. “SessionStorage in addition to protocol, domain name, port, but also under the same window.”
❞
- LocalStorage permanent storage unless manually deleted.
- The sessionStorage store disappears when the browsing period closes
- Each domain name allocates 5 MB of storage space to localStorage and sessionStorage, and 4kb of cookie
methods
SetItem ('key','value') // Store data getItem('key') // Read data remove('key') // Delete data clear() // ClearCopy the code
“⚠️ note: the Storage type is intelligent to store strings. Non-string data is automatically converted to strings before Storage, and this conversion cannot be undone when retrieving data. That is to say, you must get strings when retrieving Storage data.
Stores data for JSON objects
Storage stores data as strings, so it is best to convert JSON data to strings before saving it. This operation is called ** serialization **
Let obj = {name: 'nj ', age: 18 } localStorage.setItem('author',JSON.stringify(obj)) const author = JSON.parse(localStorage.getItem('author'))Copy the code
Similarities and differences between localStorage and sessionStorage
Similarity: the two apis are the same. They both store data in the browser, and the storage size is 5M
“Differences:”
localStorage
The stored data is permanent. The page is refreshed. The data is not lost even after the browser restarts or even the OPERATING system restartswindow
Sharing between Windows.sessionStorage
The stored data is somewhat harsh, the page refresh still works, and the data is lost when the TAB is closed. But more than one open in the same TABiframe
Data can be shared (in the case of homology).
Storage events
A Storage event is emitted whenever a Storage object changes. (Add, delete, change and check)
The event time object has four properties:
- Domain: domain for storing changes
- Key: the key to be set or deleted
- NewValue: the newValue of the key, or null if it is deleted
- OldValue: the value before the key changes
window.addEventListener('storage', e=>{
console.log(e.domain)
})
Copy the code
“ForsessionStorage
andlocalStorage
Any changes to thestorage
Events, butstorage
Events do not distinguish between the two.”
IndexedDB
❝
Indexed Database API, short for IndexedDB, is a solution for storing structured data in a browser. IndexedDB is used to replace the now-obsolete Web SQL
❞
The basic concept
- The Database:
open
Method open directly
const db = indexDB.open('testDB');
Copy the code
- Object Store: This is the Object stored in DB. This corresponds to the contents of the table in SQL. Its storage structure is as follows:
- Index: Kind of like the outer chain, it’s a kind of
Object store
, mainly used for ontologystore
Index the otherobject store
The data in it.
Var myIndex = objectStore.index('lName');Copy the code
- Transaction: A transaction is simply a collection of cruDS. If one of the links fails, the entire transaction is cancelled.
- Cursor: Is used to walk over the data contents in DB. Mainly through
openCursor
To control.
Creating a database
const request = indexedDB.open(dbName); Request. onerror = function(event) {// error handler. }; request.onupgradeneeded = function(event) { var db = event.target.result; // Set id to primaryKey var objectStore = db.createObjectStore("customers", {keyPath: "id",{autoIncrement:true}}); Objectstore.createindex ("name", "name", {unique: false}); objectStore.createIndex("email", "email", { unique: true }); };Copy the code
Create Object Store
The method used is the createObjectStore method on IDBDatabase.
const objectStore = db.createObjectStore("customers", { keyPath: "id",{autoIncrement:true} });
Copy the code
- KeyPath: Key used to set the primary key. See keyPath and generator below for details.
- AutoIncrement: Indicates whether to use the autoIncrement key feature.
“Keys are created primarily to ensure a unique identity for data insertion.”
Setting index index
After PK(Primary key) is created, we need to create index for better search performance. This can be used directly:
objectStore.createIndex('indexName', 'property', options);
Copy the code
- IndexName: Sets the name of the current index
- Property: Indicates the property referred to by index from the stored data.
Where, options has three options:
- Unique: Whether the current key can be repeated (most commonly used)
- MultiEntry: When setting the current property to an array, each element in the array is assigned an index value.
Db.createindex ('titleIndex', 'title', {unique: false});Copy the code
Add or delete data
Adding and deleting data in IndexedDB is done in a transaction. The add and delete data can be understood as a request, which is equivalent to a request that manages all the current logical operations in a transaction. So, before we start the data manipulation, we need to give you a brief introduction to how to create a transaction.
Transaction creation
Transaction API, you need to manually specify what type of operation the current transaction is.
- “Readonly” : read only
- “Readwrite” : reading and writing
- “Versionchange” : this cannot be specified manually
upgradeneeded
Automatically created in callback events. It can be used to modify existing object Store structure data, such as index, etc.
You can do this by using the TRANSACTION method on IDBDataBase after the database is opened
const transaction = db.transaction(["customers"], "readwrite"); const objectStore = transaction.objectStore("customers"); For (let I in customerData) {const request = objectStore.add(customerData[I]); request.onsuccess = function(event) { // success, done? }; }Copy the code
Operational data
After the transaction is created, we can begin to interact with the data in earnest, that is, to write our specific business logic. Below, a complete data transaction operation.
const tx = db.transaction("books", "readwrite");
const store = tx.objectStore("books");
store.put({title: "aaaaa", author: "Fred", isbn: 1111});
store.put({title: "bbbbb", author: "Fred", isbn: 2222});
store.put({title: "ccccc", author: "Barney", isbn: 3333});
tx.oncomplete = function() {
// All requests have succeeded and the transaction has committed.
};
Copy the code
The index data
Index data is the most important of all databases. Here, we can do it using index. For example, index is used to quickly index key values
const index = objectStore.index("username"); Index. OpenCursor. Onsuccess = function (event) {} / / processing success;Copy the code
Likes, favorites and comments
I am Front-end Nanjiu, thank you for your “likes, favorites and comments”, we will see you next time!
Join front-end communication group 928029210, we learn together ~