Displaying Page Visits Using Session Storage
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>11.1 Session Storage Page Visits</title> <script> function init() {/*from www . ja v a 2 s.c o m*/ // reference the div for display let divVisits = document.getElementById('divVisits'); // check if our browser supports sessionStorage if (window.sessionStorage) { let visits; // number of visits to this page // check to see if our variable exists using dot notation if (sessionStorage.visits) { // retrieve key and convert to int visits = parseInt(sessionStorage.getItem('visits')); // increment the visits visits++; } else { // default to first visit visits = 1; } // update our visits variable sessionStorage.setItem('visits', visits); // display the number of session visits divVisits.innerHTML = 'Session page visits: ' + visits; } else { // sessionStorage not available divVisits = 'Window sessionStorage is not available'; } } // onload launch our init function window.addEventListener('load', init, false); </script> </head> <body> <div id="divVisits"></div> </body> </html>