HTML5 Guidelines for Web Developers

(coco) #1
8.1 Storage 209

The central part of the JavaScript code for the example in Figure 8.1 looks
like this:


window.onload = function() {
var currDate = new Date();
sessionStorage.setItem("currenttime",
currDate.toLocaleString());
document.cookie =
"currenttime="+currDate.toLocaleString();
updateHTML();
}
function updateHTML() {
document.getElementById("currenttime").innerHTML =
sessionStorage.getItem("currenttime");
document.getElementById("currtimeCookie").innerHTML
= getCookie("currenttime");
}


As soon as the website is loaded (window.onload function), the current date (in-
cluding the time) is saved in both sessionStorage and the cookie. The updateHTML
function inserts the relevant values in two HTML elements on the website. If the
website is opened in two different browser windows, opening the second win-
dow will overwrite the cookie variable currenttime. If you then call the updateHT-
ML function in the first window, the contents of sessionStorage and cookie differ.


In the specification, sessionStorage is assigned to the top-level browsing context.
Simply put, this context can be seen as an opened browser window or an opened
tab within a browser window. A nested browsing context would be, for example,
an iframe within an HTML document. The browser also must ensure that each
website has access only to its own sessionStorage and cannot read the contents of
other websites. If this context is no longer accessible (the browser window or tab
were closed), the browser can permanently delete the associated data.


8.1.3 “localStorage”


In contrast to sessionStorage, localStorage refers only to the origin of the website,
not to the browser context. The origin is derived from the URL and consists of
the used scheme in lowercase (for example, http), the server name (also in lower-
case), and the port. If the port is not explicitly stated, the scheme’s default port is
used (for HTTP, it would be 80). The origin of the URL http://www.google.com/
about consists of the three values http, http://www.google.com, and 80.


This means that the origin in the form mentioned in the preceding paragraph
is the same for all websites on a server. Security issues ensue for web-hosting
forms, which host all users under one domain, for example, Google’s free ser-
vice sites.google.com. Because the different homepages are all in the same di-
rectory, http://sites.google.com/site, different users have access to the same

Free download pdf