将新对象添加到 chrome 本地存储

Adding new objects to chrome local storage

本文关键字:chrome 存储 添加 新对象 对象      更新时间:2023-09-26

Html code:

<select id="server">
                <option value="kr">KR</option>
                <option selected value="euw">EUW</option>
                <option value="oce">OCE</option>
                <option value="las">LAS</option>
                <option value="ru">RU</option>
                <option value="na">NA</option>
                <option value="eune">EUNE</option>
                <option value="br">BR</option>
                <option value="lan">LAN</option>
                <option value="tr">TR</option>
</select>
<input type="text" id="nickname" maxlength="16"></input></p>
<button id="save" class="flat-button">Save</button><br>

Javascritp 代码:

function save_options() {
  var server = document.getElementById('server').value;
  var prenickname = document.getElementById('nickname').value;
  var nickname = prenickname.replace(/(<([^>]+)>)/ig,""); //Remove html tags
  chrome.storage.sync.set({
    yourserver: server,
    yournickname: nickname
  }, function() {
    var status = document.getElementById('status');
  });
}

实际上,当我去保存(按下按钮)到本地存储中时,显然它会覆盖我的旧对象。我想这样做,它会添加一个新对象(如数组或列表),希望您理解我的意思。结果必须是我可以存储不同的"服务器+昵称",而不仅仅是一个。

要做你想做的事情,你需要使用一个对象数组:你将使用 chrome.storage.sync.get 获取数组的值,你将新的服务器和昵称添加到数组中,然后使用 chrome.storage.sync.set 覆盖现有值并保存它。

您的数组将如下所示:

data = [
    {yourserver: 'server1', yournickname: 'nickname1'},
    {yourserver: 'server2', yournickname: 'nickname2'},
    {yourserver: 'server3', yournickname: 'nickname3'},
    ...
];

下面是一个代码示例:

// Get all the items stored in the storage
chrome.storage.sync.get(function(items) {
    if (Object.keys(items).length > 0 && items.data) {
        // The data array already exists, add to it the new server and nickname
        items.data.push({yourserver: server, yournickname: nickname});
    } else {
        // The data array doesn't exist yet, create it
        items.data = [{yourserver: server, yournickname: nickname}];
    }
    // Now save the updated items using set
    chrome.storage.sync.set(items, function() {
        console.log('Data successfully saved to the storage!');
    });
});