DEV Community

Cover image for Day 14 of 100 Days of Code
Nkem
Nkem

Posted on • Originally published at nkem.hashnode.dev

Day 14 of 100 Days of Code

This is the final part of the chrome extension build along. The concepts I learnt were

  • Const

  • addEventListener()

  • innerHtml

  • inputvalue

  • function parameters

  • Template Strings

  • Local Storage

  • JSON objects (JSON.Stringify & JSON.Parse)

  • Objects in arrays

In the part 2, the extension did not have local storage so it was not persistent after the browser was closed. That means when the browser is closed, whatever data is put in the chrome extension would be gone. Hence the essence of the local storage.
The HTML page two more buttons added to it. The Save tab and the Delete Button. The Save button saves the value in the text box into the local storage. The SaveTab button retrieves URL into the textbox while the Delete button is for clearing the values in the box and the local storage. Below is the HTML snippet.

<html>
    <head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css">
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <input type="text" id="input-el">
        <button id="input-btn">SAVE INPUT</button>
        <button id="tab-btn">SAVE TAB</button>
        <button id="delete-btn">DELETE ALL</button>
        <ul id="ul-el">
        </ul>
        <script src="index.js"></script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Javascript code

let myLeads = []
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")
const deleteBtn = document.getElementById("delete-btn")
const leadsFromLocalStorage = JSON.parse( localStorage.getItem("myLeads") )
const tabBtn = document.getElementById("tab-btn")

if (leadsFromLocalStorage) {
    myLeads = leadsFromLocalStorage
    render(myLeads)
}

tabBtn.addEventListener("click", function(){    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        myLeads.push(tabs[0].url)
        localStorage.setItem("myLeads", JSON.stringify(myLeads) )
        render(myLeads)
    })
})

function render(leads) {
    let listItems = ""
    for (let i = 0; i < leads.length; i++) {
        listItems += `
            <li>
                <a target='_blank' href='${leads[i]}'>
                    ${leads[i]}
                </a>
            </li>
        `
    }
    ulEl.innerHTML = listItems
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
akuoko_konadu profile image
Konadu Akwasi Akuoko

Congratulations 👏👏👏

You learnt a lot, thanks for sharing