JavaScript Storage Examples

LocalStorage

<!DOCTYPE html>
<html>
<body>
    <p id="demo"></p>
    <script>  
        // Set Item
        localStorage.setItem('username', 'Khizar_Mirza');
        // Retrieve
        document.getElementById("demo").innerHTML = localStorage.getItem("username");
    </script>
</body>
</html> 
                    

SessionStorage

<!DOCTYPE html>
<html>
<body>
    <p id="theme"></p>
    <script>  
        // SessionStorage example
        sessionStorage.setItem('theme', 'dark');
        let storedTheme = sessionStorage.getItem('theme');
        document.getElementById("theme").innerHTML = storedTheme;
    </script>
</body>
</html> 
           

Cookies

<!DOCTYPE html>
<html>
<body>
    <p id="cookieOutput"></p>
    <script>  
         // Set a cookie named 'user' with the value 'Laeeque'
        document.cookie = 'user=Laeeque';
        // Retrieve the 'user' cookie's value
        let userCookie = document.cookie.split('; ').find(row => row.startsWith('user='));
        if (userCookie) {
            userCookie = userCookie.split('=')[1]; // Extract cookie value
        }
        // Display the value of the 'user' cookie in the 

tag document.getElementById('cookieOutput').innerText = Stored user cookie value: ${userCookie}; // Delete the 'user' cookie by setting its expiration date to a past time document.cookie = 'user=; expires=Thu, 01 Jan 1970 00:00:00 GMT;'; // Update the output after cookie is deleted document.getElementById('cookieOutput').innerText += '\nCookie deleted.'; </script> </body> </html>