I am new to coding and currently I am trying to build an chrome extension that acts as a little notebook and can store things inside. I have already finished a very raw example but it works totally fine. Right now the biggest obstacle is how to save the changes after closing the popup and the browser. I did some research and found that I can use localStorage
to store the data. Yet I am kinda lost and not sure where to start and how to use it.
Here is pretty much everything I have
manifest.json
{
"name": "1st extension",
"description": "Try to build an extention",
"version": "0.1",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_title": "This is my first chrome extention",
},
"permissions": ["storage"],
"options_page": "options.html"
}
popup.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<p>Type in something and save it below!</p>
<textarea id="mytext" style="width: 300px;"></textarea>
<button id="submit">Submit</button>
<button id="clear">Clear</button>
<ul id="items"></ul>
<script src="popup.js"></script>
</body>
</html>
popup.js
var myButton1 = document.getElementById("submit");
var myButton2 = document.getElementById("clear");
var itemList = document.getElementById('items');
itemList.addEventListener('click', removeItem);
//add new element into the list
function addItem(input) {
// new element
var li = document.createElement("li");
// new delete button
var deletebutton = document.createElement("button");
//add classes to btn
deletebutton.className = "delete";
// text in the delete buttion
deletebutton.appendChild(document.createTextNode('Delete'))
// text in the new element
li.appendChild(document.createTextNode(input));
// combine text and the delete button
li.appendChild(deletebutton);
// conbine the element to the list
itemList.appendChild(li);
}
//remove item from the list
function removeItem(element){
itemList.removeChild(element.target.parentElement);
}
//clear the textarea
function clear(){
document.getElementById('mytext').value = "";
};
myButton1.onclick = function() {
var myText = document.getElementById('mytext').value;
addItem(myText);
clear();
}
myButton2.onclick = function() {
clear();
}
Using storage is easy...
localStorage.setItem('Phone','1234-5678');
And reading it back...
var Phone=localStorage.getItem('Phone');
But I hope you're aware that the data won't be there in incognito windows and also... some browsers (at least mine) blow all storages away regardless, once you exit the browser.
So it's a very volatile solution and not suitable if you were looking for permanent save to the hard disk.
Let me check the Google APIs to see what else they've got for saving to the HD.
Here's one method, but dealing with blobs is not for novices...
https://developers.google.com/web/updates/2011/08/Saving-generated-files-on-the-client-side