[英]How to keep changes from the chrome extension popup after closing it using storage
I'm trying to create a todo list chrome extension that uses a popup in which the user can input text(their todo list item) and it adds to a list.我正在尝试创建一个 todo list chrome 扩展,它使用一个弹出窗口,用户可以在其中输入文本(他们的 todo 列表项)并将其添加到列表中。 I'm able to add and remove list items and make changes to the popup but I want to save their data so when they close and open the popup their todo list items are still there.
我可以添加和删除列表项并对弹出窗口进行更改,但我想保存它们的数据,因此当他们关闭并打开弹出窗口时,他们的待办事项列表项仍然存在。 I'm not too sure how to go about this as I'm new to javaScript and chrome extensions.
我不太确定如何解决这个问题,因为我是 javaScript 和 chrome 扩展的新手。 I believe you need to use storage but I'm not too sure how to implement it.
我相信您需要使用存储,但我不太确定如何实现它。
popup.html弹出窗口.html
<div class="container">
<h2 class="title">Add Items</h2>
<form id="addForm">
<input type="text" id="item">
<input type="submit" value="Submit">
</form>
<h2 class="title">List</h2>
<ul id="items" class="list-group">
<li class="list-group-item">
<button class="delete">X</button>
Click X button to delete item, type item in submit bar to add item
</li>
</ul>
</div>
popup.js弹出窗口.js
var form = document.getElementById('addForm');
var itemList = document.getElementById('items');
//form submit event
form.addEventListener('submit', addItem);
//delete event
itemList.addEventListener('click', removeItem);
//add item
function addItem(e) {
e.preventDefault();
//create delete button element
var deleteBtn = document.createElement('button');
//add classes to btn
deleteBtn.className = "delete";
//append text node
deleteBtn.appendChild(document.createTextNode('X'));
//get input value
var newItem = document.getElementById('item').value;
//create li element
var li = document.createElement('li');
//add class
li.className = 'list-group-item';
//append button to li
li.appendChild(deleteBtn);
//add text node with input value
li.appendChild(document.createTextNode(newItem));
//append li to list
itemList.appendChild(li);
savaData();
}
//remove item
function removeItem(e) {
if (e.target.classList.contains('delete')) {
var li = e.target.parentElement;
itemList.removeChild(li);
}
}
You will have to save the data in a storage.您必须将数据保存在存储器中。 Try localStorage as it is easy to use.
尝试使用localStorage,因为它易于使用。
You may combine it with JSON.stringify(<object-here>)
and JSON.parse(<string-here>)
to save objects.您可以将它与
JSON.stringify(<object-here>)
和JSON.parse(<string-here>)
起来保存对象。
Example:例子:
var my_data = {...};
// Save them
localStorage.setItem('my_date', JSON.stringify(my_data));
// Load them
my_data = JSON.parse(localStorage.getItem('my_date'));
You will have to load them from the localStorage on page load and store them every time you change the data.您必须在页面加载时从 localStorage 加载它们,并在每次更改数据时存储它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.