Introduction to the

Web Storage provides a convenient key value Storage for browsers. It is a more convenient and concise Storage method than cookies. It is also one of the most common client storage methods.

Take a look.

Local storage technology for browsers

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

Web Storage has two Storage modes:

  1. SessionStorage: A separate storage area is maintained for each access source. As long as the browser doesn’t close, the data doesn’t disappear.

So this storage is called session storage.

Note that sessionStorage is a local storage and does not transfer data to the server.

SessionStorage has a much larger storage capacity than cookies, up to 5MB.

  1. LocalStorage: similar to sessionStorage, is also used to store data, but the difference is that the data stored in localStorage will not disappear with the browser closed.

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

These two storage methods are used with 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 
Copy the code

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

For each Origin source, window. sessionStorage and window. localStorage create a new Storage object for reading data.

Web Storage-related interfaces

There are three interfaces associated with Web storage. The first is Windows. We can get sessionStorage and localStorage through window.

The second is the Storage object. The two storages 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;
}
Copy the code

We can see that Storage objects provide us with many useful methods for accessing data.

The third is the StorageEvent. When the storage detects a change, the StorageEvent will be triggered.

Browser compatibility

Let’s take a look at the compatibility of the two storages in different browsers:

Window.localStorage:

Window.sessionStorage:

As you can see, most modern browsers support both storage features.

If we are using an older browser, such as Internet Explorer 6, 7, or another browser not listed, we need to check to see if Storage is properly 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); }}Copy the code

Where type is localStorage or sessionStorage, we catch exceptions to determine whether a valid Storge object exists.

Let’s see how we use it:

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

Stealth mode

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

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

Different browsers may take different solutions.

In Safari, for example, Web Storage is available in incognito mode, but does not store anything.

Some browsers choose to clear all previous storage when the browser closes.

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

Use the Web Storage API

For Storage objects, we can access properties in the object directly like normal objects, or we can use storage.getitem () and storage.setitem () to access and set properties.

Note that the key value in a Storage object is a string. Even if you type an integer, it will be converted to a string.

In the following examples, you can set a colorSetting property:

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting'.'#a4509b');
Copy the code

We recommend using the Web Storage API: setItem, getItem, removeItem, Key, Length, etc.

In addition to setting values in Storage, we can also trigger and listen to StorageEvents.

Let’s 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;
}
Copy the code

Each time a Storage object sends a change, the StorageEvent event is emitted.

Note that changes to sessionStorage will not be triggered.

If a page in a domain changes to Storage, all other pages in the domain listen for the change. Of course, this StorageEvent cannot be listened to in any other domain.

We can add a storage event using the Window addEventListener method, 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);
});
Copy the code

In the example above, we get the Key, oldValue, newValue, URL, and Storage objects from the StorageEvent.

conclusion

The above is the basic use of Web Storage and its API.

Author: Flydean program stuff

Link to this article: www.flydean.com/web-storage…

Source: Flydean’s blog

Welcome to pay attention to my public number: “procedures those things” the most popular interpretation, the most profound dry goods, the most concise tutorial, many you do not know the small skills you find!

🏆 Mining technology essay