Web Storage

Time:2023-12-22

catalogs

1. Basic concepts

2. Functional monitoring

2.1 Testing for usability

2、W3C standard

3. Basic methods or attributes

4、 Local Storage

4.1 Description

4.2 Examples

5、sessionStorage

5.1 Description

5.2 Examples

6、StorageEvent(StorageEvent)

6.1 Constructors

6.2 Instance Properties

6.3 Example methodology

6.4 Responding to changes in storage


The Web Storage API provides storage mechanisms through which browsers can securely store key-value pairs in a more intuitive way than using cookies.

1. Basic concepts

Storage objects are simple key-value stores, similar to objects, but they remain intact when the page is loaded. Keys and values are always strings (note that, as with objects, integer keys are automatically converted to strings). You can access these values as if they were objects, or use the Storage.getItem() and Storage.setItem() methods. All three lines set the (same) colorSetting entry:
localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');
Web Storage consists of the following two mechanisms:
  • sessionStorage Maintains a separate storage area for each given origin that is available for the duration of the page session (i.e., as long as the browser is open, including page reloads and resumes).
  • localStorage Same functionality, but the data is still there after the browser is closed and then reopened.
These two mechanisms are used through the Window.sessionStorage and Window.localStorage properties (more specifically, in supported browsers)Window object implements theWindowLocalStorage respond in singingWindowSessionStorage object and hang it on itslocalStorage respond in singingsessionStorage attribute) – calling any of these objects creates a Storage object, from which you can set, get, and remove data items. For each source (origin)sessionStorage respond in singinglocalStorage Using different Storage objects – independent operation and control

2. Functional monitoring

To be able to use localStorage, we should first verify that it is supported and available in the current browsing session.

2.1 Testing for usability

Browsers that support localStorage will have a property named localStorage on the window object. However, simply asserting the existence of this property may raise an exception. If localStorage does exist, there is still no guarantee that localStorage is actually available, as various browsers provide settings to disable localStorage. Therefore, browsers may support localStorage, but not for scripts on the page. For example, the Safari browser in private browsing mode provides us with an empty l ocalStorage object with a quota of zero, effectively making it unusable. Instead, we may receive a legitimate QuotaExceededError, which means that we have used up all the available storage space, when in fact the storage space is available. Our feature detection should take these cases into account. This is a function that checks if localStorage is both supported and available:
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 above is a relatively formal example, if you use a simpler method, you can determine whether the windows storage property exists, if it does not exist is not supported by the browser, or the browser is disabled.

2、W3C standard

On April 19, 2016, the W3C’s Web Platform Working Group released Web Storage (Second Edition, Web Storage Second Edition) The official recommended standard. The specification defines a set of APIs that allow Web applications to store data on the Web client and access data in a persistent data store in the form of key value pairs (key value pair). And similar to the HTTP session information recording program, the specification also introduces two related mechanisms to allow Web applications to store the value of the name pair in the Web client can support the user in each window has its own transactions (carrying out multiple transactions in different windows at the same time), or multiple windows sharing a single Web store and spanning the current user session.

3. Basic methods or attributes

1、storage.length Returns the number of key/value pairs. 2、storage.key If n is greater than or equal to the number of key/value pairs, return the name of the nth key, or null 3、storage.getItem(key) Returns the current value associated with the given key, or null if the given key does not exist. 4、storage.setItem(key, value) Creates a new key/value pair by setting the value identified by the key to value (if the previous key does not exist). Throw QuotaExceededError DOMException Exception If the new value cannot be set. (The setting may fail. such as: the user has disabled storage or if the quota has been exceeded.)

4、 Local Storage

4.1 Description

Stored keys and valuesfrom beginning endadoptionUTF-16 stringformat, using two bytes per character. As with objects, integer keys are automatically converted to strings.

localStoragedigitalDocument-specific protocolsIn particular, for sites loaded over HTTP (e.g. In particular, for sites loaded over HTTP (e.g., ), the object returned is the same as the corresponding site loaded over HTTPS (e.g., ).

http://example.com localStorage

https://example.com localStorage

The protocols used are different, the corresponding localStorage is also different, they are isolated from each other.

For documents loaded from a URL (i.e., files opened in a browser directly from the user’s local file system, rather than served from a Web server), the behavioral requirements are undefined and may vary from browser to browser.

In all current browsers, it seems to return a different object for each URL. In other words, each URL seems to have its own unique local storage area. There are no guarantees about this behavior, however, so you should not rely on it because, as mentioned above, the requirements for URLs are still undefined. As a result, browsers may change their URL handling at any time. In fact, over time, some browsers havealreadyChanged the way it was handled. In general, the browser localStorage storage size is generally about 5M, the storage size limit, in the W3C standard does not have a clear rule to limit the size of how much, all the various browsers according to their own situation, set an upper limit.

4.2 Examples

// Get the length of the localStorage
localStorage.length   // 21

// Save to localStorage
localStorage.setItem('key', 'value');

// Get the value from localStorage
localStorage.getItem('key');

// Remove a key from localStorage
localStorage.removeItem('key');

// Clear all data saved by localStorage
localStorage.clear();

5、sessionStorage

5.1 Description

sessionStorage attribute allows you to access a sessionStorage that corresponds to the current source of the object. It is the same as the localStorage Similar, with the difference thatlocalStorage The data stored inside has no expiration time set, and the data stored in thesessionStorage The data inside will be cleared at the end of the page session.
  • The page session is maintained for as long as the browser is open, and reloading or restoring the page maintains the original page session.
  • Opening a page in a new tab or window copies the context of the top-level browsing session as the context of the new session, unlike the way session cookies work.
  • Opening multiple Tabs pages with the same URL creates the respectivesessionStorage
  • Closing the corresponding browser tab or window clears the correspondingsessionStorage

5.2 Examples

// Get the length of the sessionStorage
sessionStorage.length   // 21

// Save to sessionStorage
sessionStorage.setItem('key', 'value');

// Get the value from sessionStorage
sessionStorage.getItem('key');

// Delete a key from sessionStorage
sessionStorage.removeItem('key');

// Clear all data saved by sessionStorage
sessionStorage.clear();

6、StorageEvent(StorageEvent)

StorageEvent The interface is implemented by a storage event that is sent to the window When a storage area that the window has access to changes in the context of another document. Web Storage

6.1 Constructors

StorageEvent() Returns the newly constructed object. storageEvent

6.2 Instance Properties

In addition to the properties listed below, this interface inherits from its parent interfaceEventThe properties of the key Returns a string representing the changed key. This property is null when the change was caused by a stored method. newValue Returns the new value as a string. storageAddedReturns oldValue Returns a string for the original value, this value is newly added when the previous value is returned. StorageArea Returns a Storage object, which returns a changed object with the latest state. URL Returns a string containing the URL of the changed document.

6.3 Example methodology

In addition to the methods listed below, this interface inherits from its parent interfaceEven The methodology. initStorageEvent() Initializes the event interface in a manner similar to the similarly named initEvent() method in the DOM.

6.4 Responding to changes in storage

Whenever Storage When the object changes (i.e., when creating/updating/deleting data items, repeatedly setting the same key value will not trigger this event, and the Storage.claear() method will trigger this event at most once), StorageEvent event will trigger. Changes that occur within the same page will not work – changes that occur on other pages under the same domain (such as a new tab or iframe) will work. Pages under other domains cannot access the same Storage objects. Here is an example (open the Baidu Translate website to test):
window.addEventListener('storage', function(e) {
  console.log(e)
});
Here, we have added an event listener to the window object, which is used in the current domain-related Storage This event listener fires when the object changes. As you saw above, the event object associated with this event has several properties that contain useful information – the key of the data item that changed, the old value before the change, the new value after the change, the URL of the document where the changed storage object is located, and the storage object itself. In another tab, do the storage.
localStorage.setItem('test', 'test123')
Let’s look at the value returned by console.log(). Web Storage

Recommended Today

Resolved the Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correctly solved

Resolved Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correct solution, kiss measuring effective!!!!!! Article Catalog report an error problemSolutionscureexchanges report an error problem java.sql.SQLNonTransientConnectionException:Could not create connection to database server Solutions The error “java.sql.SQLNonTransientConnectionException:Could not create connection to database server” is usually caused by an inability to connect to the […]