Day 15 of learning JavaScript: Local storage & array in local storage

When we try to use the Chrome extension, there is a problem with storing data. The moment we click anywhere else, for example, to copy a link, the Chrome extension closes. If we open the Chrome extension again, all data we stored recently gets cleared out. That's where the local storage comes into play. Local storage is a property that allows you to store data across browser sessions. That means that if you store data in the Chrome extension, then close it and open it again, the data is still stored and doesn't get cleared out.

There are a few basic things to know about local storage. Every item consists of a key, which is connected to its value.

localStorage.setItem(key, value) // creates a new item

localStorage.getItem(key) // gets the value of the key

localStorage.clear(key) // clears local storage items

localStorage.clear() // clears the whole local storage


// both key and value need to be strings

To apply this to the Chrome extension, we have to somehow store the myLeads[] array in the local storage. The problem with this is, that we are only allowed to store strings in the local storage. The solution here is to stringify the array when we store it in the local storage.

let myLeads = [www.awesomelead.de]

// that's how you turn the array to a string:

myLeads = JSON.stringify(myLeads)

// you can also turn a string to an array:

myLeads = JSON.parse(myLeads)

// now it's an array again

When you want to check the type of a variable in JavaScript you can do it like this:

console.log(typeof xxx)

// the type gets logged out in the console

So in the JavaScript code of the Chrome extension, we just need to turn the array into a string and then create a new item for this string in the local storage:

let myLeads = []
const inputEl = document.getElementById("input-el") 
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")


inputBtn.addEventListener("click", function(){
    myLeads.push(inputEl.value)
    inputEl.value = ""

// here
    localStorage.setItem("myLeads", JSON.stringify(myLeads)) 

    renderLeads()
})



function renderLeads(){
    let listItems = ""

    for(let i = 0; i < myLeads.length; i++){
        listItems += `
            <li>
                <a href= '${myLeads[i]}' target='_blank'>
                    ${myLeads[i]}
                </a>
            </li>`
    }

    ulEl.innerHTML = listItems
}

Now the Array is stored in the local storage. However, when we refresh the Chrome extension, the leads still get deleted even tho they are saved in the local storage. Also we don't trigger the renderLeads() function right when we open the site. There are still many problems here but we will learn about it next time because we need more knowledge about a few topics.

Hopefully, you learned something valuable!