A brief discussion on the use of Web Storage API

A brief discussion on the use of Web Storage API

1. Browser local storage technology

In addition to the earliest use of cookies for local storage, modern browsers use the Web Storage API to facilitate key/value storage.

Web Storage has two storage methods:

1.1, sessionStorage

For each access source, a separate storage area is maintained. As long as the browser is not closed, the data will not disappear.

So this kind of storage is called session storage.

Note that the meaning of session here is different from that of server-side session. The sessionStorage here is only local storage and will not transfer data to the server.

The storage capacity of sessionStorage is much larger than that of cookies, which can reach 5MB.

1.2、localStorage

Similar to sessionStorage, it is also used for data storage. The difference is that the data stored in localStorage will not disappear when the browser is closed.

I can clear localStorage by setting an expiration time, deleting it manually using javascript, or clearing the browser cache.

These two storage methods are used through Window.sessionStorage and Window.localStorage. In fact, let's look at the definition of Window:

interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandlers, WindowEventHandlers, WindowLocalStorage, WindowOrWorkerGlobalScope, WindowSessionStorage

Window inherits WindowLocalStorage and WindowSessionStorage, so we can get sessionStorage and localStorage directly from Window.

For each origin, Window.sessionStorage and Window.localStorage will create a new Storage object for reading data.

2. Web Storage related interfaces

There are three interfaces related to web storage. The first is the window just mentioned. We can get sessionStorage and localStorage through window.

The second one is the Storage object. Both Storage objects obtained are Storage objects.

interface Storage {

    readonly length: number;

    clear(): void;

    getItem(key: string): string | null;

    key(index: number): string | null;

    removeItem(key: string): void;

    setItem(key: string, value: string): void;
    [name: string]: any;
}

We can see that the Storage object provides us with many useful methods to access data.

The third one is StorageEvent, which triggers the StorageEvent event when storage detects changes.

3. Browser compatibility

Let's use two pictures to see the compatibility of these two storages in different browsers:

Window.localStorage:

Window.sessionStorage:

As you can see, modern browsers basically support these two storage features.

If we are using an older browser, such as Internet Explorer 6, 7 or other browsers not listed, we need to detect whether Storage is effectively supported by the browser.

Let's see how to do the test:

function storageAvailable(type) {
    var storage;
    try {
        storage = window[type];
        var x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return e instanceof DOMException && (
            // everything except Firefox
            e.code === 22 ||
            //Firefox
            e.code === 1014 ||
            // test name field too, because code might not be present
            // everything except Firefox
            e.name === 'QuotaExceededError' ||
            //Firefox
            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
            // acknowledge QuotaExceededError only if there's something already stored
            (storage && storage.length !== 0);
    }
}

The type is localStorage or sessionStorage, and we catch the exception to determine whether there is a valid Storge object.

Let’s see how we use it:

if (storageAvailable('localStorage')) {
  // Yippee! We can use localStorage awesomeness
}
else {
  // Too bad, no localStorage for us
}

4. Incognito Mode

Most modern browsers support an incognito mode in which data privacy options such as browsing history and cookies are not stored.

So this is incompatible with Web Storage. So how to solve this problem?

Different browsers may use different solutions.

For example, in Safari, Web Storage is available in incognito mode, but nothing is stored.

Some browsers also choose to clear all previous storage when the browser is closed.

Therefore, during the development process, we must pay attention to the different processing methods of different browsers.

5. Using the Web Storage API

For Storage objects, we can directly access the properties in the object like ordinary objects, or we can use Storage.getItem() and Storage.setItem() to access and set properties.

Note that the key values ​​in the Storage object are all of string type. Even if you enter an integer, it will be converted to a String.

The following examples can all set a colorSetting property:

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');

Although all three methods can achieve storage and access functions, we recommend using the Web Storage API: setItem, getItem, removeItem, key, length, etc.

In addition to setting the values ​​in Storage, we can also trigger and listen to StorageEvent.

Let's take a look at the definition of StorageEvent:

interface StorageEvent extends Event {

    readonly key: string | null;

    readonly newValue: string | null;

    readonly oldValue: string | null;

    readonly storageArea: Storage | null;

    readonly url: string;
}

Whenever a Storage object sends a change, a StorageEvent event is triggered.

Note that if the sessionStorage changes, it will not be triggered.

If a page in a domain has a Storage change, then other pages in the domain will monitor the change. Of course, if it is other domains, this StorageEvent cannot be monitored.

We can add storage events through the addEventListener method of window, as shown below:

window.addEventListener('storage', function(e) {  
  document.querySelector('.my-key').textContent = e.key;
  document.querySelector('.my-old').textContent = e.oldValue;
  document.querySelector('.my-new').textContent = e.newValue;
  document.querySelector('.my-url').textContent = e.url;
  document.querySelector('.my-storage').textContent = JSON.stringify(e.storageArea);
});

In the above example, we get the key, oldValue, newValue, url and Storage object from StorageEvent.

The above is a brief discussion of the details of using the Web Storage API. For more information about the Web Storage API, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to use SessionStorage and LocalStorage in Javascript
  • How to use localStorage in JavaScript
  • Vue based on localStorage storage information code example
  • Vue uses localstorage to implement breadcrumbs
  • JS+HTML5 local storage Localstorage to implement registration, login and verification function example
  • An example of using vuex to store user information in localStorage
  • JavaScript learning tutorial: cookies and webstorage
  • Detailed explanation of how to use localStorage in vue
  • Vue interface refresh data is cleared localStorage usage detailed explanation
  • HTML5 WebStorage (HTML5 local storage technology)

<<:  How to deploy LNMP & phpMyAdmin in docker

>>:  MySQL 8.0.15 installation graphic tutorial and database basics

Recommend

Detailed explanation of mandatory and implicit conversion of types in JavaScript

Table of contents 1. Implicit conversion Conversi...

Introduction and use of five controllers in K8S

Table of contents Controller type of k8s Relation...

Import csv file into mysql using navicat

This article shares the specific code for importi...

Vue uses canvas to realize image compression upload

This article shares the specific code of Vue usin...

Prevent HTML and JSP pages from being cached and re-fetched from the web server

After the user logs out, if the back button on the...

How to use CSS counters to beautify ordered lists of numbers

In web design, it is very important to use an org...

MySQL deadlock routine: inconsistent batch insertion order under unique index

Preface The essence of deadlock is resource compe...

Shtml Concise Tutorial

Shtml and asp are similar. In files named shtml, s...

How to deploy nodejs service using Dockerfile

Initialize Dockerfile Assuming our project is nam...

JavaScript operation element examples

For more information about operating elements, pl...

About the problems of congruence and inequality, equality and inequality in JS

Table of contents Congruent and Incongruent congr...

Detailed explanation of the execution process of mysql update statement

There was an article about the execution process ...