简体   繁体   English

如何使用chrome.storage.sync.remove从数组中删除一项?

[英]How do I delete one item from an array with chrome.storage.sync.remove?

I'm building a Chrome browser extension which includes a feature that lets users save urls. 我正在构建一个Chrome浏览器扩展程序,其中包括一项允许用户保存网址的功能。 I used chrome.storage.sync to create this feature and didn't encounter any issues. 我使用chrome.storage.sync创建了此功能,但没有遇到任何问题。

However, I also need to let users delete urls they've already saved. 但是,我还需要让用户删除他们已经保存的网址。 I created a text input box where they can enter a single url they want to delete (ie "www.url.com"). 我创建了一个文本输入框,他们可以在其中输入要删除的单个网址(即“ www.url.com”)。 I want to convert this input into a string and use it to remove a matching string from Chrome storage when the user presses a button. 我想将此输入转换为字符串,并在用户按下按钮时使用它从Chrome存储中删除匹配的字符串。

I thought the chrome.storage documentation specifies that chrome.storage.sync.remove can be used to remove a string from a stored array, but I can't get it to work. 我以为chrome.storage文档指定了chrome.storage.sync.remove可用于从存储的数组中删除字符串,但我无法使其正常工作。 Here's my code: 这是我的代码:

function removeUrl() {
    var theUrl = document.getElementById('url-input').value;
    chrome.storage.sync.get(null, function(result, error) {

        // Checks if the array (urlList) exists:
        if ('urlList' in result) {
            var theList = result['urlList'];

            // Checks if the url that will be deleted is in the array:
            if (theList.includes(theUrl)) {
                chrome.storage.sync.remove(theUrl);
                chrome.runtime.reload();
            }
        }
        // Error handling goes here
    });
}

This code doesn't throw any errors, but it doesn't remove the url from the array either. 此代码不会引发任何错误,但也不会从数组中删除该url。

Please note that I only want to delete 1 url at a time, there are no duplicate urls in the array, and I am not using any libraries like jQuery. 请注意,我一次只想删除1个网址,数组中没有重复的网址,并且我没有使用jQuery之类的任何库。 What am I doing wrong? 我究竟做错了什么?

You cannot do it this way, because chrome.storage is a key-value storage. 您无法以这种方式执行此操作,因为chrome.storage是键值存储。

In your particular example, you are trying to remove from storage one element of the array, but storage contains only key with array. 在您的特定示例中,您尝试从存储中删除数组的一个元素,但是存储仅包含带有数组的键。

The best solution here will be just removing this value from the array and set the array to the chrome.storage again. 最好的解决方案是从数组中删除该值, chrome.storage再次将数组设置为chrome.storage

var theList = result['urlList'];

// Checks if the url that will be deleted is in the array:
if (theList.includes(theUrl)) {

  // create a new array without url
  var newUrlList = arr.filter(function(item) { 
    return item !== theUrl;
  });

  // set new url list to the storage
  chrome.storage.sync.set({ 'urlList': newUrlList });
  chrome.runtime.reload();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM