Further Exploration
The <canvas> HTML5 is an exciting technology, one that oers considerably more
than I have had a ch ance to put on these few pages. You c an also use a canvas to work
with other graphic elements such as patterns, curves, pixels, text, and images. You
can make elements transparent, add shadows, and you can apply coordinate system
transform ations. And yes, you can d etect mouse clicks over certain areas of the c anvas
to create interactive graphics. I therefore encourage anyone who feels he/she could
make a great use of this tempting techn ology to search among countless sources of
informa tion to find out more about it. For example, the book
HTML5 Canvas by Steve
and Je Fulton oer s a decent start.
B.2 Local Data Storage through Web Storage
As soon as you’re connected to the web , there are two places where you can store
your data: on the web server (server-side) or on your own computer (c lient-side).
Both have their pros and cons, and you ’ll learn which type of storag e works best for
which purpose as you progress in your web programming proficiency. However, as
you can read in the paragraph about security concerns later in this section, sensitive
data definitely belongs to a web server and not to a client computer.
Web application s and even web documents can imp rove tre mendously if you furnish
them with some client-side memory. You ca n program web pages to stor e data such
as user preferences or even save the complete state of the page, so y our visitor al-
ways finds a page exactly as he/she left it at the end of his/her last visit. In the early
days of the Internet, storing user data was on ly possible on a server. This was soon
recogn iz ed as a drawback because of excessive storage a nd retrieval load on servers
for tasks that could b e managed locally by a client. As early as in 1994, Netscape
Communica tions used cookies (a type of client-side data storage) to implement a re li-
able virtual shopping cart to store items a user selected f rom dierent pages of a site,
possibly across multiple visits. Online shopping sites today almost exclusively store
selected items in a database on the server side. For many web applications, however,
local data storage capability has become indispensable, especially when it comes to
running web applications oine. This makes web applications look and feel more like
real applications.
For a long time, cookies were the only c lient-side data storage mechanism arou nd.
However, they were d esigned for use by ser ver-side scripts and it was quite awkward
to utilize them from client-side programs. As the HTML 5 Web Storage API became
universally available, cookies slowly turned back to their initial role as a client-side
storage instrument for server-side scripts.
Apart fr om the Web Storage, there exist some other local storage technologies, but
none of them succeeded in getting the level of standardization that Web Storage did.
The poten tially exciting Filesystem API, conceptualized to work with a private local
filesystem utilizing file-based stora ge mech anisms familiar to most programmers, was
pronounced dead in April 2014 because of little inte rest shown by the majority of
browsers. Also of interest was a client-side database support, w hose standardization
eorts also failed and tha t is n ot implemented equally in all browsers.
B.2. Local Data Storage through Web Storage 279
localStorage and sessionStorage Objects
The Web Storage API is composed of two objects, localStorage a nd session
Storage, w hich are defined as properties of the Window object. Both objects are
in fact associative arrays that store key-value p airs and implement exactly the same
set of methods and properties. The only dierence between them is their scope and
persistence, which define who can access the data and for how long.
Data stored in a sessionStor age object—as the name suggests—are roughly limited
to a single browser tab, both in their scope and persistence. If y ou ope n the same
document in two dierent tabs, each of them will have its own sessionStorage
object, which mean s that scripts from one tab cannot access (neither read nor write)
data stored by scripts from the other tab. Data stored in a se ssionStorage object
will be deleted as soon as you close the tab associated with th em.
On the other hand, data stored in the localStorage object stay on the users com-
puter forever, or at least until a web application explicitly deletes them or a u ser clears
them thr ough the browser’s user interface. Besides, localStorage has a broade r
scope than sessionStorage—it is scoped by the origin of a document. The docu-
ment origin is determined by a protocol, a hostname , and a port, and a change to any
of these also changes the d ocument origin. For example, the following four URLs
represent four dierent document origins:
http://w w w.nowheresite.com
https://www.nowheresite.com
(A dierent pro col)
http://w w w.nowhere-site.com (A dierent hostnam e)
http://w w w.nowheresite.com:42 (A dierent port)
All documents with the same origin share data from a sing le localStora ge object,
which means that they can read as well as override each others data.
Note that p hysical memory used to store local d ata is set aside by the browser and can-
not be accessed by browsers of other vendors. This eectively limits localStorage
scope to a specific browser vendor as well. So, if you visit a site using one browser,
you cannot access data stored during that v isit through another browser, even if you
are viewing the same site within the same origin.
Storage API
As already mentioned, the localStorage and sessionStorage objects store asso-
ciative arrays of key-value pairs. One way of using these objects is that you simply
set and query their properties as you can do with any other JavaScript object. For
example, you can stor e a counter with a value of one in either of the following two
ways:
localStorage.counter = 1;
localStorage["counter"] = 1;
280 Appendix B. Ways to Continue
Note that a ll values are eventually sto red a s strings even if you p rovide other data
types. So, if you want to increment the stored c ounter, be careful to convert it to a
number before incrementing its value:
localStorage.counter += Number(localStorage.counter) + 1;
While storing and retrieving data by setting and querying properties of storage objects
is convenien t, it is often better to use special m ethods to ma nage data storage. For one
thing, they are safer and provide m ore functionality. To store and retrieve a value, you
use the metho ds se tItem() and g etItem(), respectively:
localStorage.setItem("counter", 1); //Stores a counter with a
//value of one
c = localStorage.getItem("counter"); //Retrieves the counter value
Don’t forget that values a re always stored as strings, so getItem() returns a string
too.
You can also delete a particular value or even dele te all stored values using the methods
removeItem() and clear( ), respectively. For example:
localStorage.removeItem("counter"); //Removes the counter from
//storage
localStorage.clear(); //Removes all stored values
Like regular JavaScript arrays, localStorage and sessionStorage also have the
length property. But this property works dierently in that it always holds the num -
ber o f stored values. Recall that the length property of Ar ray is o ne bigg er than the
largest ar ray index, and is not equal to the number of elemen ts whe n an array is sparse.
The key() method of the localStorage and sess ionStorage objects allows you
to enumerate the names of all stored values b y passing numbers from zero to length
- 1 to it. As an example, the next cod e fragment writes to the JavaScript Console all
the values stored in localStorage:
for (i = 0; i < localStorage.length; i++) {
name = localStorage.key(i);
console.log(localStorage.getItem(name));
}
An Example
As a more realistic example, imagine that you want to add a memo utility to your
website, so that y our visitor could write down his/her thoughts and be able to read
them d uring his/her next visit.
To do that, you first need to include an <textarea> HTML element:
B.2. Local Data Storage through Web Storage 281
<textarea id="memo" rows="5" cols="100">
The JavaScript pa rt of the exam ple needs to do three things: First, it has to get a
referenc e to the <textarea> element. Second, it needs to read the previously stored
text from localStorage (if it exists) and write it to the <textarea> element. Finally,
it has to react to any change to the text inside the <textarea> element and save it to
localStorage. Here’s complete code imp le menting all three tasks:
window.onload = function() {
m = document.getElementById("memo");
//If the item exists, get its value from localStorage and show it
//inside <textarea>:
if (localStorage.getItem("text")) {
m.value = localStorage.getItem("text");
}
//Every time the content of <textarea> is changed, store the new
//content to localStorage:
m.oninput = function() {
localStorage.setItem("text", this.value);
};
};
Synchronizing Pages with Storage Events
Each time the data stored in localStorage or sessionStorage changes, a stor-
age event is fired on any tabs or windows that are currently displaying pages with
the same origin. However, it is not fire d on the wind ow that cau sed the change. A
storage event can conveniently b e used to synchronize all the pag es a u ser is view-
ing, so that a change that a user makes in on e window is immediately reflecte d in
other w indows or tabs as well. A programmer can utilize this event by implement-
ing the onstorage event handler, whic h is a prop erty of the Window object. While
Web Storag e is a mongst the better supported HTM L5 features, the storage event it-
self is not fully and e qually supported in all browsers. For example, if you want
your co de to also work in Firefox, you should attach the storage event usin g the Win-
dow’s addEventListener() method, instead of directly defining the onstora ge
event handler. However, the addEventLis tener() method is not covered in this
book.
Security Concerns
When a web browser oers to remember a password for you, it stores it securely in
encryp te d form on your h ard drive. That said, the Web Storage mechanism does not
encryp t data before saving it, an d sto red data is freely accessible to uninvited snoopy
users sharing access to the computer as well as to malicious software that might lurk
in the system. For this reason, never use any for m of client-side storage for storing
sensitive user data like passwords or credit card number s.
282 Appendix B. Ways to Continue
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.4.206