gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:10:40 28 4
gpt4 key购买 nike

我正在构建一个 Chrome 浏览器扩展程序,其中包含一项允许用户保存网址的功能。我使用 chrome.storage.sync 创建此功能,没有遇到任何问题。

但是,我还需要让用户删除他们已经保存的网址。我创建了一个文本输入框,他们可以在其中输入要删除的单个网址(即“www.url.com”)。我想将此输入转换为字符串,并在用户按下按钮时使用它从 Chrome 存储中删除匹配的字符串。

我以为chrome.storage documentation指定 chrome.storage.sync.remove 可用于从存储的数组中删除字符串,但我无法让它工作。这是我的代码:

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

此代码不会引发任何错误,但也不会从数组中删除 url。

请注意,我只想一次删除 1 个 url,数组中没有重复的 url,并且我没有使用任何像 jQuery 这样的库。我究竟做错了什么?

最佳答案

你不能这样做,因为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();
}

关于javascript - 如何使用 chrome.storage.sync.remove 从数组中删除一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784369/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com