HTML and CSS Reference
In-Depth Information
Thus, Web Storage is racy , meaning it's susceptible to race conditions. As a result, you
need to take precautions to ensure the integrity of your data and the accuracy of any
queries. As mentioned earlier, the only mechanism to prevent race conditions is the
StorageEvent.
Race conditions can occur with multithreaded browsers, as well, because threads can
cause problems when saving data. Here's a good example:
var myarray = [ a , b ];
var first = myarray . splice ( 0 , 1 );
localStorage . first = first ;
You would expect the following:
localStorage . first == a ; //true
When a race condition occurs, we could find that this happens:
localStorage . first == b ; //true
As one thread splices myarray and is de-scheduled, another thread runs the same code
segment and effectively reads myarray as only having one element, b , and as such, assigns
it to first.
Bottom line, the exact same problem exists with cookies, which doesn't seem to have
bothered people much. If race conditions are a problem (or you think they're going to
be a problem), you need a more advanced storage mechanism than Web Storage, such
as IndexedDB or a solution that can support transactions and write-locks.
Using JSON to Encode and Decode
To store a JavaScript object (or an array perhaps) in your localStorage or session
Storage , you need to use JSON to encode and decode your data, as in:
var mydata = {
"Book" : "HTML5 Architecture" ,
"Author" : "Wesley Hales" ,
};
Next, store the JavaScript object as a string:
localStorage . setItem ( "mydata" , JSON . stringify ( mydata ));
When you're ready to retrieve the data, use:
JSON . parse ( localStorage . getItem ( "mydata" ));
Security and Private Browsing
All this communication between client and server raises security issues. They come in
two flavors: keeping your app secure and private browsing by users.
Search WWH ::




Custom Search