Java Reference
In-Depth Information
<body>
<script>
var pageViewCount = localStorage.getItem("pageViewCount");
var pageFirstVisited = localStorage.getItem("pageFirstVisited");
var now = new Date();
if (pageViewCount == null) {
pageViewCount = 0;
pageFirstVisited = now.toUTCString();
}
var oneMonth = new Date(pageFirstVisited);
oneMonth.setMonth(oneMonth.getMonth() + 1);
if (now > oneMonth) {
pageViewCount = 0;
pageFirstVisited = now.toUTCString();
}
pageViewCount = parseInt(pageViewCount, 10) + 1;
localStorage.setItem("pageViewCount", pageViewCount);
localStorage.setItem("pageFirstVisited", pageFirstVisited);
var output = "You've visited this page " + pageViewCount +
" times since " + pageFirstVisited;
document.write(output);
</script>
</body>
</html>
Save this as
ch13 _ question1.html
.
The first two lines get two values from
localStorage
and store them in variables. The first holds
the number of visits, the second the date the page was first visited. You also create a variable to
contain the current date:
var pageViewCount = localStorage.getItem("pageViewCount");
var pageFirstVisited = localStorage.getItem("pageFirstVisited");
var now = new Date();
If the
pageViewCount
key does not exist in
localStorage
, the variable of the same name is
null
,
and you'll need to initialize the
pageViewcount
and
pageFirstVisited
variables with
0
and the
current date, respectively. Remember that
localStorage
contains only string data, so you use the
Date
object's
toUTCString()
method to convert the date to a string:
if (pageViewCount == null) {
pageViewCount = 0;
pageFirstVisited = now.toUTCString();
}