Querying for local storage entry without throwing errors - javascript

Working on a chrome extension. I am using the following to save some data to my local storage:
chrome.storage.local.set({ [variablyNamedEntry]: someObjectToBeSaved });
Elsewhere in my code I want to query if the entry exists and if it does, I will want to local some variable "myVar" with the object.
If the entry exists, this code works to achieve my goals:
chrome.storage.local.get(null, function(result){
myVar = result[variablyNamedEntry];
}
But if no entry exists for "variablyNamedEntry" it throws an error. I could manage this error with a try/catch sequence. But that can't be the best approach, given that I know that it will not find the entry a very large percentage of the time.
How can I achieve my goal?
Update:
I tried using:
chrome.storage.local.get([variablyNamedEntry], function(result){
if (result != undefined)
myVar = result[variablyNamedEntry];
}
But I still get the following error if the entry does not exist:
extensions::uncaught_exception_handler:8 Error in response to storage.get: TypeError: Cannot read property 'someProperty' of undefined

Please be aware the items parameter for the callback of chrome.storage.local.get is always an object and would never be undefined.
Assuming you have a key-value in which key is 'Sample-Key', you could use the following code
chrome.storage.local.get(null, function(result){
if(typeof result['Sample-Key'] !== 'undefined') {
console.log(result['Sample-Key']);
}
});
Or
chrome.storage.local.get('Sample-Key', function(result){
if(typeof result['Sample-Key'] !== 'undefined') {
console.log(result['Sample-Key']);
}
});

Related

Error when removing items from chrome local storage

I'm trying to get my chrome extension (service worker) to detect when a tab is open to add an object to storage and when a tab is closed to remove the corresponding item from storage. However I'm receiving an error on removal:
Error handling response: TypeError: Error in invocation of storage.remove([string|array] keys, optional function callback): Error at parameter 'keys': Value did not match any choice.
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab)=>{
if (changeInfo.title && tab.status == "complete") {
try {
chrome.storage.local.set({[tabId]:changeInfo})
}
catch(error) {
console.log(error)
}
}
});
chrome.tabs.onRemoved.addListener((tabId, removeInfo)=>{
chrome.storage.local.remove([tabId]) <---- ERROR HERE
})
To make sure the content of the storage I also tried the following to make sure the storage has the object and the key to remove it with:
chrome.tabs.onRemoved.addListener((tabId, removeInfo)=>{
chrome.storage.local.get(null, (storage) => {
console.log(storage)
chrome.storage.local.remove([tabId])
})
})
Been stuck on this for a while so any recommendations are appreciated.
You are giving remove an array of keys ([tabId]), but Storage.removeItem takes a single string representing a storage entry's key.
Try to replace
chrome.storage.local.remove([tabId])
with
chrome.storage.local.remove(tabId)

Check if json object is undefined in Node.js

I'm getting this error "TypeError: Cannot read property '0' of undefined" when I want to extract a data from JSON file.
However, the data I want to extract is not available every time I request a JSON file, therefore, I'm getting this error which makes my Node.js Application to crash every time I'm getting this error.
simply check if it exists or not:
if (json && json['Name'] && json['Name']['Nationality']) {
data = json['Name']['Nationality'][0];
} else {
// no data, do whatever error handling you want here
}
A solution for this sort of problem is using try-catch:
try {
data = json['Name']['Nationality'][0];
} catch (error) {
data = "Sorry no data found"
}
The try function is going to run the code if it did find any error it will pass it to catch.

Dynamoose/DynamoDB update saving empty array as null

I'm using the Node.js package Dynamoose to handle DynamoDB requests in my web application.
Problem is when I try to update the item whenever the JSON object includes an empty array Dynamoose seems to set that to null. Or it could be DynamoDB for all I know.
Below is part of my schema that I'm using for this table.
var NoteSchema = new dynamoose.Schema({
_id: String,
details: Array
});
In the code below the variable body is set to {details: []}. I have confirmed this by running console.log(body);.
Note.update({
_id: searchid
}, body, function(err, note) {
if (err) {
console.log(err);
} else {
console.log(note);
}
});
Problem is inside that callback function when running console.log(note); details doesn't even show up at all. So it's null or undefined. In the Amazon Web Services again details doesn't exist at all for that entry.
What is so strange is when creating a new Note, setting details = [], and saving that, details is an empty array and works perfectly. So to me it seems like a specific problem with updating the record and setting that property to an empty array, since creating a record and setting that property to an empty array works perfectly.
How can I update the record and set details to an empty array?
Figured this out. Submitted this issue to the GitHub repo. Basically the following line (lib/Model.js about line 396) of code checks to see if the value is an array with length = 0. If so it will delete that JSON key before sending it to AWS.
if(val === null || val === undefined || val === '' || (Array.isArray(val) && val.length === 0)) {
I submitted a pull request using my fork. In that pull request I made the change to allow an optional JSON object parameter of options to be passed into the update function. This is the 3rd parameter of the update function and right before the callback function. If there is a key called emptyarrayallowed and that value is set to true then you that line above will get changed into the following.
if(val === null || val === undefined || val === '') {
For example in my example above changing the update function to the following will work (as long as you are using my fork or the pull request has been approved).
Note.update({_id: searchid}, body, {"emptyarrayallowed": true}, function(err, note) {
if (err) {
console.log(err);
} else {
console.log(note);
}
});
Let me know if you have any questions regarding this solution.
Small update on Charlie's answer. The functionality was merged as mentioned by Charlie. However, looks like the property name was renamed to allowEmptyArray from emptyarrayallowed.

chrome.storage not working as expected

I am trying to save a list of dictionary objects in the chrome storage. But the following code seems to not work as expected.
When the extension loads for the first time and there is no goal object in the storage, runtime.lasterror object should be set and the code in that part should get executed. But it isn't.
When I uncomment the chrome.storage.sync.set line and save the object and the next time I call the function expecting it to save a list, it doesn't. It does not give any of the alert boxes.
function isPgUrl(pg_url,gl_name) {
if(pg_url && gl_name) {
dic_url={
"name":gl_name,
"pg_url":pg_url
}
//chrome.storage.sync.set({"goal":[dic_url]});
chrome.storage.sync.get(["goal"], function(data) {
if(chrome.runtime.lastError) {
chrome.storage.sync.set({"goal":[dic_url]},function() {
alert("blah");
});
alert("here");
return;
}
var list=data.goal;
list.append(dic_url);
alert(list);
chrome.storage.sync.set({"goal":list},function() {
alert("lalala");
return;
});
});
}
}
You'll never get chrome.runtime.lastError set for missing data. It's not an exception - you just get undefined value. So your check should be:
if(!data.goal) { ... }
or
if(typeof data.goal === "undefined") { ... }
If you uncomment that line, you need to be aware that chrome.storage is asynchronous: the data is not in storage until the callback of .set(). So your .get() that is executed immediately after calling .set() may get a snapshot of the older view of the storage - making your code fail at list.append(dic_url);
Not that Array.prototype.append exists in the first place. You should be using .push().
Chrome Storage has a more efficient way of setting a default-if-not-in-storage value, by using an Object as a query:
chrome.storage.sync.get({key: "defaultValue"}, function(data) {
// data.key will be the stored value, or "defaultValue" if not in storage
});
So, if I understand the purpose of your code correctly (append dic_url to goal in storage), this will do it:
// Makes more sense to default to empty list
chrome.storage.sync.get({goal: []}, function(data) {
var list = data.goal;
list.push(dic_url);
chrome.storage.sync.set({goal: list}, function() {
// Stoarge updated, dic_url appended to goal
});
// Storage is not yet updated - set() is async
});
// Storage is not yet updated - get()/set() are async

check if JSON object exist in sessionstorage javascript

I am working on a site where some data is stored in the session. On the first page I need to check if the json object is already in the session.
This is the code that fails.
var passedTotaal = JSON.parse(sessionStorage.getItem('test totaal array'));
if(passedTotaal.hasOwnProperty('letterplaatnaam')){
//do something
}
When the JSON object exist it works else I get the following error:
Uncaught TypeError: Cannot read property 'hasOwnProperty' of null
I know this is because its empty.
I have looked at different stackoverflow questions but i couldn't find an answer
If there is any need for more information please let me know.
Try:
if(passedTotaal!=null && passedTotaal.hasOwnProperty('letterplaatnaam'))
var test = sessionStorage.getItem('test totaal array');
if (test) {
var passedTotaal = JSON.parse(test);
if(passedTotaal && passedTotaal.hasOwnProperty('letterplaatnaam')){
//do something
}
}
because getItem can return null as well

Categories

Resources