The Web storage mechanism, which is mainly about the storage mechanism provided by the Web Storage API, allows the browser to safely store key-value pairs, which is more intuitive than using cookies. The next step is simply to understand how to use this technique.
Basic concepts
Web Storage consists of two mechanisms:
sessionStorage
Maintains a separate storage area for each given source, which is available during a page session (that is, as long as the browser is open, including page reload and recovery)
localStorage
The same functionality, but the data still exists after the browser shuts down and then reopened
Both of these mechanisms are Window.sessionStorage
used by and Window.localStorage
attributes. More specifically, objects are implemented in supported browsers and Window
WindowLocalStorage
WindowSessionStorage
objects are hung localStorage
under their and sessionStorage
properties. Invoking any of these objects creates Storage
an object through which Storage
the data item can be set, fetched, and removed. For each source sessionStorage
and localStorage
use a different Storage
object.
For example, a call in the document localStorage
will return an Storage
object, and the call sessionStorage
returns a different Storage
object. These objects can be manipulated in the same way, but the operation is independent.
Before you know how to use localStorage
and sessionStorage
before, come to the Storage
object first.
Storage Object
Storage
Object as an interface to the Web Storage API, Storage
providing access to session storage or local storage under a specific domain name. For example, you can add, modify, or delete stored data items.
If you want to manipulate the session store for a domain name, you can use it Window.sessionStorage
if you want to manipulate the local storage of a domain name Window.localStorage
.
Storage properties and methods for objects
Storage
object to provide its own properties and methods:
Storage.length
: Returns an integer that represents Storage
the number of data items stored in the object. This is Storage
a property of the object and is a read-only property.
Storage.key()
: The method takes a numeric value n
as a parameter and returns the first n
key name in the store
Storage.getItem()
: The method takes a key name as a parameter and returns the value corresponding to the key name.
Storage.setItem()
: The method takes a key name and value as a parameter, it adds a key-value pair to the store, and if the key name exists, updates its corresponding value
Storage.removeItem()
: This method takes a key name as a parameter and removes the key name from the store
Storage.clear()
: Calling this method empties all the key names in the store
A simple example
To write a simple example, the page has three buttons: Set
, Get
and Remove
. When the button is clicked, three functions are bound separately: setStorage()
, getStorage()
and removeStorage()
:
setStorage()
: Do localStorage
and sessionStorage
store, while the key name is stored, the name
key value isW3cplus.com
getStorage()
: Get stored name
, and print out
removeStorage()
: Removes setStorage()
the stored in functionname
Take a look at the effect of the operation.
First click on the Set
button. Using the browser developer tool, we can see Local Storage
and Session Storage
all save a name
key name, its corresponding key value is W3cplus.com
. As shown in the following:
Local Storage
Session Storage
By clicking the button at this time Get
, you can get the setStorage()
stored name
value separately and output:
Next, click the Remove
button again to open the developer tools, view Local Storage
and Session Storage
options, you can see that the original corresponding Key
and Value
was emptied, such as the following Session Storage
:
At this time, click the Get
button again, the output is as null
follows:
What we see above is the first phenomenon. Let's look at the second kind. Click Set
the button First, then click the Get
button, you can see the following output content:
The same page, do not do Remove
button operation, directly close the browser window, and then reload the page, and directly click on Get
the button to see the page output content:
You can see what the localStorage
output is, and what the W3cplus.com
output has sessionStorage
become null
. From this effect also validates the aforementioned: sessionStorage
and localStorage
Similarly, allows you to access an Storage
object, but accesses an object sessionStorage
session Storage
, and localStorage
accesses an object local Storage
. Another difference is that the localStorage
data stored in it does not have an expiration time setting, and the data stored in sessionStorage
it is erased at the end of the page session. A page session remains in the browser while it is open, and reloading or resuming the page still maintains the original page session. Opening a page in a new tab or window initializes a new session (the one that is localStorage
key
value
still saved, and sessionStorage
key
value
The one that is erased).
Basic usage of local storage
The previous example has also been shown, and the following example is taken localStorage
:
Localstorage.setitem (' key ', ' value '); Set a localstorage name called ' key ' Localstorage.getitem (' key '); Gets the stored localstorage, gets the ' key ' corresponding to the value ' Localstorage.removeitem ' (' key '); Remove the stored localstorage, remove the name ' key ' Localstorage.clear (); Delete all the Localstorage
It can be encapsulated for ease of use.
Set Localstorage
function Setlocalstorage (key, value) { return Localstorage.setitem (key, value);}
Get Localstorage
function Getlocalstorage (key) { return Localstorage.getitem (key);}
Remove Localstorage
function Removelocalstorage (key) { return Localstorage.removeitem (key);}
Note: sessionStorage
Use methods and localStorage
similar.
Exception handling
localStorage
In the current browser environment, is not completely stable, there may be a variety of problems, so in the setting localStorage
must consider exception handling. localStorage
exception handling is typically used try/catch
to catch/handle exceptions. So we need to add in the setup localStorage
try/catch
, so the previous setLocalStorage()
function can be modified to:
function Setlocalstorage (key, value) { try { Localstorage.setitem (key, value); } catch (e) { if ( E.name = = = ' Quota_exceeded_err ' | | E.name = = = ' ns_error_dom_quota_reached ') { console.log ("error:local Storage limit exceeds."); Localstorage.clear (); } else { Console.log ("error:saving to local storage.");}}}
If you consider more browser compatibility, we can also modify the above code to:
function Setlocalstorage (key, value) { try { Localstorage.setitem (key, value); } catch (e) { if ( Isquotaexceeded (e)) { Console.log ("error:local Storage limit exceeds."); Localstorage.clear (); } else { Console.log ("error:saving to local storage.");}}} function isquotaexceeded (e) { var quotaexceeded = false; if (e) { if (e.code) { switch (e.code) {case] : quotaexceeded = true; break; Case 1014: //Firefox if (e.name = = = ' ns_error_dom_quota_reached ') { quotaexceeded = true; } break; } } else if (e.number = = = -2147024882) { //IE8 quotaexceeded = true; } } return quotaexceeded;}
Expiry time
In terms of localstorage
, its native does not support setting the expiration time, if you want to set, you can only encapsulate a layer of logic to implement:
function Setlocalstorage (key, value) {var curtime = new Date (). GetTime ();//Get current time//convert to JSON string sequence var valuedat E = json.stringify ({val:value, timer:curtime}); try {localstorage.setitem (key, valuedate);//Set JSON string to store value} catch (e) {if (isquotaexceeded (e)) { Console.log ("Error:local Storage limit exceeds."); Localstorage.clear (); } else {Console.log ("error:saving to local storage."); }}}function isquotaexceeded (e) {var quotaexceeded = false; if (e) {if (e.code) {switch (e.code) {Case 22:quotaexceeded = True ; Break Case 1014://Firefox if (e.name = = = ' ns_error_dom_quota_reached ') { Quotaexceeded = true; } break; }} else if (e.number = = = -2147024882) {//IE8 quotaexceeded = true; }} return quotaexceeded;} function Getlocalstorage (key,exp) {var vals = Localstorage.getitem (key);//get local stored value var dataobj = Json.parse (Vals); Converts a string to a JSON object//if (the current time-the stored element is set at the time it was created) > expiration time var istimed = (new Date (). GetTime ()-Dataobj.timer) > Exp if (istimed) {Console.log ("expires"); } else {var newvalue = Dataobj.val; } return newvalue;}
This time we call:
Setlocalstorage (' name ', ' Hello, w3cplus.com! '); var localkey = getlocalstorage (' name ', 2); Console.log (Localkey);
If we exp
change the time:
Setlocalstorage (' name ', ' Hello, w3cplus.com! '); var localkey = getlocalstorage (' name ', 0); Console.log (Localkey);
Role domain
( image from: 1190000004121465)
The domain name mentioned here does not refer to the scope of the function. and localStorage
the scope of the store. So it refers to how to separate the pages from each other localStorage
. localStorage
as long as the same protocol, the same hostname, the same port, you can read and modify to the same localStorage
stored data. Rather sessionStorage
than localStorage
more stringent, in addition to protocol, hostname, port, also requires in the same window.
Capacity limits
localStorage
There are sessionStorage
certain restrictions on and storage, the industry is basically unified for, is much 5M
cookies
larger than the 4K
general situation is enough to use. If the amount of storage is greater than the maximum value, each browser throws an error QUOTA_EXCEEDED_ERR
.
Browser compatibility
So far the WEB storage has been supported by a number of mainstream browsers, with support for browsers that can be consulted through caniuse.com.
Summarize
Recently in the creation of the project, encountered the requirements of local storage, previously contacted, in order to better understand and understand the knowledge of Web local storage, took a little time to learn the relevant knowledge, and made some notes. Because of the knowledge of beginners, inevitably there is a mistake, if there is wrong, but also ask the colleague to make bricks. In addition, a special article "How I Detect and use Localstorage" is recommended in @mathias. can help you better understand the localStorage
relevant knowledge. If you have a better tutorial or experience, you are welcome to share it with us in the comments below.
Original: http://www.w3cplus.com/javascript/web-storage.html©w3cplus.com
How to use the Web storage mechanism-sessionstorage,localstorage