11

Tôi đang viết tiện ích mở rộng chrome và tôi không thể lưu trữ mảng. Tôi đọc rằng tôi nên sử dụng JSON stringify/parse để đạt được điều này, nhưng tôi có một lỗi bằng cách sử dụng nó.Lưu trữ một mảng với chrome.storage.local

chrome.storage.local.get(null, function(userKeyIds){ 
    if(userKeyIds===null){ 
     userKeyIds = []; 
    } 
    var userKeyIdsArray = JSON.parse(userKeyIds); 
    // Here I have an Uncaught SyntaxError: Unexpected token o 
    userKeyIdsArray.push({keyPairId: keyPairId,HasBeenUploadedYet: false}); 
    chrome.storage.local.set(JSON.stringify(userKeyIdsArray),function(){ 
     if(chrome.runtime.lastError){ 
      console.log("An error occured : "+chrome.runtime.lastError); 
     } 
     else{ 
      chrome.storage.local.get(null, function(userKeyIds){ 
       console.log(userKeyIds)}); 
     } 
    }); 
}); 

Làm cách nào để lưu trữ một mảng đối tượng như {keyPairId: keyPairId, HasBeenUploadedYet: false}?

+1

Không cần để stringify/phân tích nó. Bạn có thể lưu trữ mảng trực tiếp. – BeardFist

+0

@BeardFist Tôi có Loại lỗi không được phép: Đối tượng # không có phương pháp 'đẩy' cho mã sau, đó là lý do tại sao tôi nghĩ tôi nên xâu chuỗi của mình. 'chrome.storage.local.get (null, function (userKeysIds) { if (userKeysIds === null) { userKeysIds = new Array();} userKeysIds.push ({keyPairId: keyPairId, HasBeenUploadedYet: false}); // ERROR chrome.storage.local.set (userKeysIds, function() { } }); }); ' –

+0

Bạn nhận và đặt công cụ bằng cách sử dụng 'keys' và khi bạn nhận được nó, nó là một đối tượng như 'chrome.storage.local.get ('userKeyIds', hàm (stuff) {console.log (stuff.userKeyIds);});' – BeardFist

Trả lời

27

Tôi nghĩ bạn đã nhầm localStorage cho Chrome Storage API mới.
- Bạn cần chuỗi JSON trong trường hợp của localStorage
- Bạn có thể lưu trữ đối tượng/mảng trực tiếp với mớiStorage API

// by passing an object you can define default values e.g.: [] 
chrome.storage.local.get({userKeyIds: []}, function (result) { 
    // the input argument is ALWAYS an object containing the queried keys 
    // so we select the key we need 
    var userKeyIds = result.userKeyIds; 
    userKeyIds.push({keyPairId: keyPairId, HasBeenUploadedYet: false}); 
    // set the new array value to the same key 
    chrome.storage.local.set({userKeyIds: userKeyIds}, function() { 
     // you can use strings instead of objects 
     // if you don't want to define default values 
     chrome.storage.local.get('userKeyIds', function (result) { 
      console.log(result.userKeyIds) 
     }); 
    }); 
}); 
+3

Điều đó hoạt động hoàn hảo, cảm ơn rất nhiều! Và mẹo hay cho các giá trị mặc định :) –

+1

Không sao, tôi rất vui được giúp đỡ. – galambalazs

+0

Làm thế nào để dữ liệu được retrived với 'userKeyIds' cuối cùng đó là một chuỗi, khi chúng tôi đang thiết lập các khóa như đối tượng userKeyIds? Mã dường như hoạt động tốt. – mik

Các vấn đề liên quan