What is the

Web Storage is a data Storage mechanism provided by HTML5 specifically for browser Storage. It is divided into Local Storage, Session Storage, and IndexDB

why

  1. Large Storage capacity: Web Storage The Storage capacity ranges from 5 to 10 MBIT/s depending on the browser.
  2. It is only on the browser side and does not communicate with the server.

Local Storage and Session Storage

The difference lies in the lifecycle and scope.

  1. Life cycle: Local Storage is persistent Local Storage. Data stored in it will never expire. The only way to make it disappear is to manually delete it. Session Storage is temporary local Storage. It is session-level Storage. When the Session ends (the page is closed), the Storage content is also released.

  2. Scope: Local Storage, Session Storage, and Cookie all follow the same origin policy. However, the special point of Session Storage is that even if two pages under the same domain name are not opened in the same browser window, their Session Storage content cannot be shared.

Local Storage

It is also textual content, in the form of key-value pairs.

  1. Use it to store some content stable resources. For example, image-rich e-commerce sites will use it to store Base64 image strings.
  2. It will also be used to store some static resources such as CSS and JS that are not updated frequently.
  3. Persistent, large data storage space.
  • Store data: setItem()
localStorage.setItem('user_name'.'wxh')

Copy the code
  • Read data: getItem()
localStorage.getItem('user_name')

Copy the code
  • Remove data corresponding to a key name: removeItem()
localStorage.removeItem('user_name')
Copy the code
  • Clear data records: clear()
localStorage.clear()
Copy the code

Session Storage

It is also textual content, in the form of key-value pairs.

  1. Suitable for storing synchronized session level information.
  2. This information only applies to the current session and needs to be updated or released when you start a new session.
  3. Can be used to store your browsing footprint for this session.
  4. Timeliness: Close the browser and destroy session information.
  5. The page session remains as long as the browser is open, and the original page session remains when the page is reloaded or restored.
  6. The top-level browsing session context is copied as the context for the new session when a new TAB or window opens a page.
  7. Opening multiple Tabs pages of the same URL creates their own sessionStorage.
  8. Closing the corresponding browser TAB clears the corresponding sessionStorage.
  • Store data: setItem()
sessionStorage.setItem('user_name'.'wxh')

Copy the code
  • Read data: getItem()
sessionStorage.getItem('user_name')

Copy the code
  • Remove data corresponding to a key name: removeItem()
sessionStorage.removeItem('user_name')
Copy the code
  • Clear data records: clear()
sessionStorage.clear()
Copy the code

IndexDB

IndexDB is a non-relational database that runs on a browser.

  1. IndexDB has no storage upper limit (generally no less than 250 MB).
  2. It can store binary data as well as strings.
  • Open/create an IndexDB database
  // In the following callback, we can get the database instance via event.target.result
  let db
  // Parameter 1 is the database name, and parameter 2 is the version number
  const request = window.indexedDB.open("wxhDB".1)
  // Use a listener function when IndexDB fails
  request.onerror = function(event) {
     console.log('IndexDB cannot be used')}/ / success
  request.onsuccess  = function(event){
    // Get the db instance here
    db = event.target.result
    console.log("You opened IndexDB")}Copy the code
  • Create an Object Store (object store corresponds to the “table” unit in the database).
The // onupgradenneeded event is called when the database is initialized/version updated and we create an Object Store in its listener function
request.onupgradeneeded = function(event){
  let objectStore
  // Create a test table if the same table has not been created before
  if(! db.objectStoreNames.contains('test')) {
    objectStore = db.createObjectStore('test', { keyPath: 'id'}}})Copy the code
  • Build a transaction to perform some database operations, such as adding or extracting data.
  // Create a transaction and specify the table name and read/write permissions
  const transaction = db.transaction(["test"]."readwrite")
  // Get the Object Store
  const objectStore = transaction.objectStore("test")
  // Write data to the table
  objectStore.add({id: 1.name: 'wxh'})

Copy the code
  • Wait for the operation to complete by listening for the right type of event.
// The listener function when the operation succeeds
transaction.oncomplete = function(event) {
  console.log("Operation successful")}// The function that listens when the operation fails
transaction.onerror = function(event) {
  console.log("There's an Error here.")}Copy the code

Tool function

var storage = {
    / * * to manipulate local data relevant methods, such as localStorage and sessionStorage encapsulation * /
    setStorage: function(key, value, duration) {
        var data = {
            value: value,
            expiryTime: !duration || isNaN(duration) ? 0 : this.getCurrentTimeStamp() + parseInt(duration)
        };
        localStorage[key] = JSON.stringify(data);
    },
    getStorage: function(key) {
        var data = localStorage[key];
        if(! data || data ==="null") {
            return null;
        }
        var now = this.getCurrentTimeStamp();
        var obj;
        try {
            obj = JSON.parse(data);
        } catch (e) {
            return null;
        }
        if (obj.expiryTime === 0 || obj.expiryTime > now) {
            return obj.value;
        }
        return null;
    },
    removeStorage: function(key){
        localStorage.removeItem(key);
    },
    getSession: function(key) {
        var data = sessionStorage[key];
        if(! data || data ==="null") {
            return null;
        }
        return JSON.parse(data).value;

    },
    setSession: function(key, value) {
        var data = {
            value: value
        }
        sessionStorage[key] = JSON.stringify(data);
    },
    getCurrentTimeStamp: function() {
        return Date.parse(new Date()); }};Copy the code