Javascript Local Storage

Introduction

Using local storage, create a page that keeps track of how many times the page has been visited by the user in the last month.

View in separate window

<!DOCTYPE html> 
<html lang="en"> 
<body> 
    <p id="demo"></p>
    <script> 
        let pageViewCount = localStorage.getItem("pageViewCount"); 
        let pageFirstVisited = localStorage.getItem("pageFirstVisited"); 
        let now = new Date(); // ww w.  j a  v  a 2 s .c  om

        if (pageViewCount == null) { 
            pageViewCount = 0; 
            pageFirstVisited = now .toUTCString(); 
        } 

        let 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); 

        let output = "You've visited this page " + pageViewCount + 
            " times since " + pageFirstVisited; 

        document.getElementById("demo").innerHTML = output; 
    </script> 
</body> 
</html> 



PreviousNext

Related