HTML and CSS Reference
In-Depth Information
The command localStorage.setItem("lastdate",olddate) sets up a new key/value pair or replaces
any previous one with the key equal to lastdate . The statement
last = localStorage.getItem("lastdate");
assigns the fetched value to the variable last . In the code for our simple example, we just display the
results. You can also check for something being null and provide a friendlier message.
The command localStorage.removeItem("lastdate") removes the key/value pair with lastdate as
the key.
For our simple date application, we set the onClick attribute of each button object to be some JavaScript
code. For example:
<button onClick="javascript:store();">Store date info. </button>
causes store() to be invoked when the button is clicked.
You may be wondering if anyone can read any of the saved information in local storage. The answer is that
access to each key/value pair in localStorage (and in other types of cookies) is restricted to the Web
site that stored the information. This is a security feature.
The Chrome browser allows testing of local storage with HTML5 scripts stored on the local computer.
Firefox does not. This means that to test these applications in Firefox, youll need to upload the file to a
server.
Because browsers may not support local storage or there may be other problems such as exceeding limits
set by the user for local storage and cookies, it is a good practice to include some error checking. You can
use the JavaScript function typeof to check if localStorage is accepted by the browser:
if (typeof(localStorage)=="undefined")
Figure 7-14 shows the result of loading the date application and clicking on the Store date info button in an
old version of Internet Explorer. (By the time you read this topic, the latest version of IE may be out and
this will not be a problem.)
Figure 7-14. The browser didnt recognize localStorage .
JavaScript also provides a general mechanism for avoiding the display of errors. The compound
statement try and catch will try to execute some code and if it doesnt work, go to the catch clause.
try {
olddate = new Date();
localStorage.setItem("lastdate",olddate);
 
Search WWH ::




Custom Search