Java Reference
In-Depth Information
Load ch13 _ example3a.html into a browser. This page behaves exactly like Example 2a. The first
time you go to the main page, there will be nothing but a heading saying “Welcome to Example 3a.”
Refreshing the page displays the “What's New?” link in the page. Clicking this link takes you to
ch13 _ example3b.html .
As before, we'll focus on the JavaScript contained within ch13 _ example3b.html .
First, you declare the lastUpdated variable:
var lastUpdated = new Date("Tue, 28 Dec 2020");
Next, you get the date of the user's last visit from local storage with the lastVisit key:
var lastVisit = localStorage.lastVisit;
This assigns one of two values to the lastVisit variable. If this is the user's first visit to the page, the
localStorage.lastVisit key won't exist and returns null to lastVisit . In which case, you won't
display the What's New? link in the document.
The second possible value of lastVisit is a string representation of the date the user last visited the
page. In this situation, you need to check whether the user visited the site before it was last updated and
direct the user to the What's New? page if so:
if (lastVisit) {
lastVisit = new Date(lastVisit);
if (lastVisit < lastUpdated) {
document.getElementById("whatsNew").innerHTML =
"<a href='ch13_example3b.html'>What's New?</a>";
}
}
Remember that the data stored in local storage is strings; so, you create a new Date object based on the
value of lastVisit and store it in the lastVisit variable. Then, if lastVisit is less than lastUpdated ,
you display the What's New? link in the document.
In the final line of code, you reset the value of the localState.lastVisit key:
localStorage.lastVisit = new Date();
Viewing Web storage Content
Like cookies, you can also view the data stored in web storage, but doing so requires you to use
the features found in each browser's development tools. You learn about the development tools
found in Internet Explorer, Chrome, and Firefox in Chapter 18, but viewing the web storage
content in Chrome is straightforward. Simply press F12 to bring up the development tools and
click the Resources tab. Figure 13-20 shows you the local storage for the beginningjs.com
domain.
 
Search WWH ::




Custom Search