How to store multiple items in Chrome Extension Storage? [duplicate] - javascript

I'm writing a chrome extension, and I can't store an array. I read that I should use JSON stringify/parse to achieve this, but I have an error using it.
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)});
}
});
});
How could I store an array of objects like {keyPairId: keyPairId,HasBeenUploadedYet: false} ?

I think you've mistaken localStorage for the new Chrome Storage API.
- You needed JSON strings in case of the localStorage
- You can store objects/arrays directly with the new Storage 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)
});
});
});

Related

Javascript - Array is of type object and failing at .push directly after declaration of array

const audio = connection.receiver.createStream(message, { mode: 'pcm', end: 'manual' });
var testingArr = new Array();
audio.on('data', (data) => {
console.log(Array.isArray(testingArr)); //output: false
testingArr.push(data);
});
The body here shows testingArr as not of type array
How is this happening?
I am looking to add the new data to the array as it comes in over a few seconds so I can decrypt it into text strings.
I have also tried var testingArr = [], and encountered the same issue
The Error I get when I attempt to run this script:
TypeError: testingArr.push is not a function
at Decoder.<anonymous>
I accidentally set testingArr to another value outside of the async process farther down in the script.

Google Apps Script PropertiesService Unexpected Token in Obj Literal

I am using Google Apps PropertyService to store some settings variables. When I use the setProperties() function and give it an object (just like they do in the documentation) and then try to get a property and parse it I am getting a SyntaxError: Unexpected Token in Object Literal.
The PropertiesService is emptied before I run this code. As far as I understand I am getting a string back that I should be able to parse into an object.
function setDefaults(){
var def = {
config: {
isSetup: false
},
test: {
page: true
}
}
var docServ = PropertiesService.getDocumentProperties();
docServ.setProperties(def, true);
log(typeof docServ.getProperty("config")); //string
log(docServ.getProperty("config")); //{isSetup=false}
log(JSON.parse(docSer.getProperty("config"))); //SyntaxError
}
It seems that the issue has something to do with multiple nested objects. Apparently, the JSON parser can only go down one level.
Calling JSON.stringify() on each of the nested objects solved the problem for me:
var def = {config: {isSetup: false}, test: {page: true}};
for (var prop in def) {
def[prop] = JSON.stringify(def[prop]);
}
var docServ = PropertiesService.getDocumentProperties();
docServ.setProperties(def, true);
var config = JSON.parse(docServ.getProperty("config"));
Logger.log(config.isSetup); //logs 'false'

How to track ADD errors in indexedDB?

I want to add multiple lines of data into an IndexedDB. The data will be parsed from CSV file, each line has an id. Only new id's should be added to the DB, so I use add. This works well so far.
But how can i find out, which lines/objects where NOT added? (because of duplicate id's) If I use onerror and inspect the object e on console of chrome, I can not find the object, which I send to the DB. So i only know, something was not added, but not what it was. So how to track this?
// ....
for (var key in csvObject.data ) {
var request = store.add(csvObject.data[key]);
}
request.onerror = function(e) {
console.log(e); // e contains not the value of CSVobject.data[key]
};
You should do this. Write the function within the loop and pass your object as an argument to it.
for (var key in csvObject.data) {
(function(obj) {
var request = store.add(obj);
request.onerror = function(e) {
console.log(obj, e.target.error, e.target.source); // some error messages
};
})(csvObject.data[key]);
}

Properly storing an object in chrome.storage?

I'm trying to store an object in my chrome extension containing other objects using chrome.storage - but am having trouble initializing it and properly fetching it using chrome.storage.sync.get. I understand that I'm supposed to get objects in the form of chrome.storage.sync.get(key: "value", function(obj) {} - the issue is I'm not sure how to
Initialize the object the first time with get
Properly update my object with set
I have the following code to create the object and add the data I need.
allData = {};
currentData = {some: "data", goes: "here"};
allData[Object.keys(allData).length] = currentData;
This will correctly give me an object with it's first key (0) set to currentData. (Object: {0: {some: "data", goes: "here"}}) Working as intended, and allData[Object.keys(allData).length] = currentData; will properly push whatever currentData is at the time into my Object later on.
But how do I properly store this permanently in chrome.storage? chrome.storage.sync.get("allData", function(datas) {}) fails to create an empty allData variable, as does allData: {}, allData = {}, and a variety of different things that return either undefined or another error. How do I properly initialize an empty object and store it in chrome.storage? Or am I going about this all wrong and need to break it down into associative arrays in order for it to work?
I essentially need that small block of working code above to be stored permanently with chrome.storage so I can work with it as needed.
You first need to set the data inside the storage:
allData = {};
currentData = {some: "data", goes: "here"};
// to initialize the all data using the storage
chrome.storage.sync.get('allData', function(data) {
// check if data exists.
if (data) {
allData = data;
} else {
allData[Object.keys(allData).length] = currentData;
}
});
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'allData': allData}, function() {
// Notify that we saved.
message('Settings saved');
});
After that you should be able to access the data using the chrome.storage.sync.get('allData', function(){ ... }) interface.
You can easily do this with the new JavaScript (ECMAScript 6), have a look into Enhanced Object Properties:
var currentData = {some: "data", goes: "here"};
chrome.storage.local.set({allData: currentData });
In the old way, was something like this:
var obj = {};
var key = "auth";
obj[key] += "auth";
obj[key] = JSON.stringify({someKey: someValue});

Push method in JavaScript

Hi I have a problem in javascript.
when i try to save info in the localStorage in console i had the error 'method 'push' of undefined.
<script type="text/javascript">
//localStorage.clear(); // Clears the hard drive (database)
var oUsers = {aIds:[], aNames:[]};
// Default
if(localStorage.sUsers){
console.log('Users already in memory');
// Get the string with users from the database and
// convert it into an object, so we can use it
oUsers = JSON.parse(localStorage.sUsers);
}
function SaveUser(){
// Take the text and make it an object
oUsers.aIds.push(document.getElementById("TxtId").value);
oUsers.aNames.push(document.getElementById("TxtName").value);
localStorage.sUsers = JSON.stringify(oUsers);
console.log(localStorage.sUsers);
}
</script>

Categories