微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Chrome 扩展 - 如何在 .localStorage 中存储多个用户输入

如何解决Chrome 扩展 - 如何在 .localStorage 中存储多个用户输入

希望一切顺利!只是一个简单的问题,我是编程新手,并决定使用 vanilla JS 进行 chrome 扩展来锻炼 ol' 编码肌肉(此时非常小)。此扩展的一部分是从 popup.html/popup.js 文件获取用户输入并将其存储在 background.js 中的 localStorage 中。

我目前已经设置了从 popup.js 到 background.js 的消息传递(但如果您发现有任何更改,请告诉我)。后台脚本似乎是设置 .localStorage 函数的地方——唯一的问题是我还没有完全弄清楚如何在 localStorage 中存储多个变量。但是,我已经能够“稍微”弄清楚如何存储单个输入,直到用户输入另一个值,然后原始值被覆盖。

我对程序这部分的最终目标是能够存储尽可能多的用户输入值(意味着每次单击“提交”按钮时,都会在本地存储中添加一个值已经在那里了)。

代码如下:

popup.html:


<body>

  <div class="main_container">
    <form id="main_input">
      <h1>Please enter data</h1>
      <input id="name_textBox" />
      <button id="button1">OK</button>
    </form>

  </div>

  <script src="popup.js"></script>
</body>

popup.js:

    // User Input Field Values
function userInput(e) {
  //e.preventDefault();
  const inputValue = document.getElementById("name_textBox").value;
  //console.log(inputValue);
  chrome.runtime.sendMessage({popupVal: inputValue.trim(),msgType:'userInput'});
};

//Call User Input Value When Button On Popup is Clicked!

document.addEventListener("DOMContentLoaded",function() {

  chrome.storage.local.get(['popupObj'],function(result) {
    console.log('Value currently is ' + JSON.stringify(result));
    if (result && result.popupObj) 

document.getElementById("name_textBox").value=result.popupObj.popupVal || '';
  });

document.getElementById("button1").addEventListener("click",userInput);

});

background.js:

// Messaging From the popup! //


  chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse) {
        console.log("background.js got a message")
        sendResponse("recieved");
        if (request.msgType==='userInput') {
            chrome.storage.local.set({key: request},function() {
                localStorage.setItem("website",JSON.stringify(request));
                //Parse and then store as an array

              // Get the existing data
              var existing = localStorage.getItem('website');

              // Create an array
              // Otherwise,convert the localStorage string to an array
              existing = existing ? existing.split(',') : [];

              // Add new data to localStorage Array
              existing.push(JSON.stringify(request));

              // Save back to localStorage
              localStorage.setItem('website',existing.toString());

})
        }
    }
);

我读到将输入​​存储在数组中将是来自用户的多个变量的最理想选择?还有其他建议吗?

此外,如果您建议在显示的原始问题之上更改任何内容,请告诉我(:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。