InterviewSolution
Saved Bookmarks
| 1. |
Explain Web Storage in HTML5. |
|
Answer» HTML5 introduced the feature to store DATA in the browser. This is a very useful feature, which can be used by developers to store user data when they visit the site. There are two types of Web Storage in HTML5 -
The local storage can be accessed using localStorage and session storage can be accessed using sessionStorage. In the below example, we are storing the number of hits in both localStorage and sessionStorage. But if we close the browser, the Session Storage count again starts from 1 but in Local storage, it persists. <!DOCTYPE html> <html> <head> <title>Web storage</title> <style> .grid__iframe { display: grid; place-content: center; } </style> <script type="text/javascript"> window.onload = function(){ if (sessionStorage.hits) { sessionStorage.hits = Number(sessionStorage.hits) + 1; } else { sessionStorage.hits = 1; } if( localStorage.hits ) { localStorage.hits = Number(localStorage.hits) +1; } else { localStorage.hits = 1; } document.getElementById("local").innerHTML = `Total Hits Local Storage: ${localStorage.hits}`; document.getElementById("session").innerHTML = `Total Hits Session Storage: ${sessionStorage.hits}`; }; </script> </head> <body> <div class="grid__iframe"> <h1>Refresh the page to increase number of hits.</h1> <h2>Close the window and open it again</h2> <h4>The Local Storage Count will remain, but Session storage will start from 1</h4> <div ID="session"></div> <div id="local"></div> </div> </body> </html> |
|