简体   繁体   中英

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. I used chrome.storage.sync to create this feature and didn't encounter any issues.

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"). 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.

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. 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.

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. What am I doing wrong?

You cannot do it this way, because chrome.storage is a key-value 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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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