Chrome управление состоянием расширения - PullRequest
0 голосов
/ 12 июля 2020

В настоящее время я делаю расширение chrome (это мое первое расширение chrome), с которым вы можете делать небольшие заметки и хотите сохранить вводимые пользователем данные. Я сохраняю пользовательский ввод внутри классов ввода. Как мне сохранить состояние расширения chrome, чтобы при повторном открытии оно оставалось прежним? Вот код, который я написал до сих пор.

//selectors
const addbutton = document.querySelector(".add");
const addlist = document.querySelector(".note-list");
const noteList = document.querySelector(".note-list")

//event listners
addbutton.addEventListener('click', addNote);

//functions
function addNote(event){
    //prevent page refresh
    event.preventDefault();
    //note div
    const noteDiv = document.createElement('div');
    noteDiv.classList.add('note');
    //create li
    const newNote = document.createElement('li');
    newNote.classList.add('noteitem');
    noteDiv.appendChild(newNote);
    //create input
    const newInput = document.createElement('input');
    newInput.classList.add('noteInput')
    newNote.appendChild(newInput);
    //append to list
    noteList.appendChild(noteDiv);
}
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    outline: none;
}
body{
    height: 500px;
    width: 400px;
}

h1{
    font-family: "Montserrat", sans-serif;
    font-size: 20px;
    font-weight: lighter;
    padding-top: 10px;
    padding-bottom: 10px;
    
}
main{
    text-align: center;
}
.title{
    box-shadow: 0 2px 2px -2px rgba(0, 0, 0, 0.685);
}
.mainpage{
    padding-top: 20px;
}

.add{
    font-family: "Montserrat", sans-serif;
    font-size: 25px;
    font-weight: 400px;
    background-color: #00FF33;
    width:40px ;
    height: 40px;
    border-radius: 10px;
    border: none;
    transition: ease 0.5s;
}

.add:hover{
    background-color: #00c026;
}

.note-container{
    display: flex;
    justify-content: center;
    align-items: center;
}

.note-list{
    min-width: 30%;
    list-style: none;
}

.note{
    margin: 0.5rem;
    background: whitesmoke;
    font-size: 1.5rem;
    display: flex;
    justify-content: space-between;
    border-radius: 7px;
}
.noteitem{
    padding: 0.5rem 2rem;
}

.noteInput{
    display: block;
    margin-right: auto;
    margin-left: auto;
    border: none;
    background-color: whitesmoke;
    font-size: 20px;
    max-height: 200px;
    
}

.note li{
    flex: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mini Note</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <main>
        <div class="title">
            <h1>Mini note app</h1>
        </div>
        <section class="mainpage">
            <button class="add">+</button>
            <div class="note-container">
                <ul class="note-list"></ul>
            </div>
        </section>
    </main>
    <script src="/popup.js"></script>
</body>
</html>

Спасибо

Ответы [ 2 ]

0 голосов
/ 17 июля 2020
// uses local storage
chrome.storage.local.set({key: value}, function() {
  console.log('Value is set to ' + value);
});

// uses synced storage, hits Chrome backend when being set
chrome.storage.sync.set({key: value}, function() {
  console.log('Value is set to ' + value);
});

// to retrieve the data, use 'sync' instead of 'local' if using sync
chrome.storage.local.get(['key'], function(result) {
   console.log('Value currently is ' + result.key);
});

Вам все равно нужно будет выяснить, как вы хотите организовать данные заметки. Например, вы можете сохранить все заметки в массиве на ключе notes, который выглядит следующим образом:

{
  notes: [
    { id: 1, body: 'First note' },
    { id: 2, body: 'Second note' }
  ]
}
0 голосов
/ 14 июля 2020

у вас есть два варианта: -

  • вы можете использовать localStorage так же, как на веб-странице, чтобы узнать больше проверьте здесь

  • вы можете использовать chrome.storage для получения дополнительных проверьте здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...