If you've ever visited the Lowe's web site and performed a search, you may have noticed the site remembers your last search and pre-populates the search box with your last search string. How is this accomplished? It's a simple use of the browser's localStorage object.

localStorage allows a web site to persist information about a user across multiple browser sessions as simple key-value pairs of data. The key is a name you assign to a piece of information (such as "lastSearch") and the value is the data you want to persist (such as "snow blower"). You can examine the contents of Chrome's localStorage by opening the Developer Tools and viewing the "Application" section.

Interacting with localStorage in JavaScript is rather simple.

// Save information to localStorage.
localStorage.setItem("lastSearch", "snow blowers");

// Retrieve information from localStorage.
var lastSearch = localStorage.getItem("lastSearch");

To mimic the behavior of the Lowe's search box, we just need to connect this code to some browser events. We can start with initializing the search box when the browser finishes loading the page.


document.addEventListener("load", () => {
    let searchField = document.forms["search"].elements["search"];
    searchField.value = localStorage.getItem("lastSearch");
});

If "lastSearch" doesn't exist within localStorage, the return value of getItem will be null and the search box will be initialized with empty text.

Now we just need to save the search text any time the form is submitted.

document.addEventListener("load", () => {
    let searchForm = document.forms["search"];

    let searchField = searchForm.elements["search"];
    searchField.value = localStorage.getItem("lastSearch");

    searchForm.addEventListener("submit", () => {
        localStorage.setItem("lastSearch", searchField.value);
    });
});

And that's all there is to using localStorage to remember the user's last search on a web site.


You can inspect the form below to see this in action.