Open In App

HTML DOM Window localStorage Properties

HTML DOM Window localStorage Properties allow you to store value pairs in web browsers using objects. It is a read-only

property. This object is not expired even if the browser is closed. So, the data is never lost.



Return Values: It returns  a Storage object.

Syntax:



Example1: This example describes the Save, Read and Remove data to localStorage.




<!DOCTYPE html>
<html>
  
<head>
    <title> HTML DOM Window localStorage Properties </title>
    <script>
      
    //Saving data locally
    function save() {
        var fieldValue = document.getElementById('textfield').value;
        localStorage.setItem('text', fieldValue);
    }
        
    // Reading data
    function get() {
        var storedValue = localStorage.getItem('text');
        if(storedValue) {
            document.getElementById('textfield').value = storedValue;
        }
    }
        
    // Removing stored data
    function remove() {
        document.getElementById('textfield').value = '';
        localStorage.removeItem('text');
    }
    </script>
</head>
  
<body onload="get()">
    <p1>
        Type something in the text field and 
        It will Get stored locally by Browser 
     </p1>
    <input type="text" id="textfield" />
    <input type="button" value="save" onclick="save()" />
    <input type="button" value="clear" onclick="remove()" />
    <p2>
        when you reopen or reload this page,
        your text is still there.
    </p2>
    <p3>
        <br>click on clear to remove it.</p3>
</body>
  
</html>

Output:

Window localStorage

Example 2: This example describes the check storage type and saves data.




<!DOCTYPE html>
<html>
  
<head>
    <title>HTML DOM Window localStorage Properties</title>
</head>
  
<body>
    <div id="SHOW"></div>
    <script>
    if(typeof(Storage) !== "undefined") {
        localStorage.setItem("name", "GeeksforGeeks");
        document.getElementById("SHOW").innerHTML = 
        localStorage.getItem("name");
    } else {
        document.getElementById("SHOW").innerHTML = 
        "YOUR BROWSER DOES NOT" + "SUPPORT LOCALSTORAGE PROPERTY";
    }
    </script>
</body>
  
</html>

Output:

Window localStorage Property

Supported Browsers: The browser supported by DOM Window localStorage are listed below:


Article Tags :