繁体   English   中英

将新对象添加到Chrome本地存储中

[英]Adding new objects to chrome local storage

HTML代码:

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

暂无
暂无

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

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