how to remove the chrome.storage.local - javascript

Im not getting how remove chrome.storage.local values in javascript?
i use like this but the storage value is not removing from the store:chrome.storage.local.remove(result.MyFile.Base64File);
Please check the below code, here I'm using chrome.storage.local.set to set
var obj = { DocName: "name", Base64File: "Base64string" };
chrome.storage.local.set({ 'MyFile': obj });
and chrome.storage.local.get to retrive the values
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
}

Note: You can not remove values, you can remove indexes with specific names what causes that they gets removed WITH there values.
Tbh I could not run the code but I'm pretty sure something like this should work. But I really recommend you to avoid chrome.storage because it's some kind of "dumb" :)
So please have a look at this code:
function clearItem(symbol) {
var remove = [];
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
if (index == "symbol") remove.push(index);
});
chrome.storage.sync.remove(remove, function(Items) {
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
console.log("removed: " + index);
});
});
});
});
};

Related

update only specified element with chrome.storage.local.set

I have an array in chrome local storage, format:
{"flights":
[
{"end":"2018-02-10","price":"476","start":"2018-02-01","tabId":1129367822},
{"end":"2018-02-11","price":"493","start":"2018-02-01","tabId":1129367825},
{"end":"2018-02-12","price":"468","start":"2018-02-01","tabId":1129367828}
]
}
Now I'm updating all data this way:
function updateValue(index, item) {
chrome.storage.local.get(['flights'], function (response) {
response.flights[index] = item;
chrome.storage.local.set({flights: response.flights});
});
}
But there is problem with async requests, because I have several request at the time. Some requests get old data and save it again in storage...
I want to update only specified element (for example flights[0] with new data), but it doesn't work...
Something like this, but workable:
chrome.storage.local.set({flights[0]: item});
Is there any way to do this? Or maybe you have some advices to resolve this issue other way.
many thanks for any help
Based on terales' answer (that code has some errors).
I make it this way:
function parseFlight(result) {
let flightsArray = [];
Object.keys(result).forEach(function (key) {
if (key.includes('flight')) {
let index = key.replace('flight_', '');
flightsArray[index] = result[key];
}
});
return flightsArray;
}
function updateValue(index, item) {
let flightPrefix = 'flight_';
let obj = {};
obj[flightPrefix + index] = item;
chrome.storage.local.set(obj);
}
chrome.storage.local.get(null, function (result) {
let flights = parseFlight(result);
});
Thanks for help!
You can save each flight into a separate key and get all flights by traversing all storage:
cosnt flightPrefix = 'flight_';
function updateValue(index, item) {
chrome.storage.local.set({flightPrefix + index: item});
}
function getFlights() {
// Pass in null to get the entire contents of storage.
chrome.storage.sync.get(null, function(items) {
let flights = Object.keys(items).filter(key => key.beginsWith(flightPrefix));
console.log(flights);
});
}

Ionic/Angular: Read and Write Array in Local Storage

I'm working with Ionic framework as part of an online course I'm taking to learn AngularJS and a great many other tools useful to a web developer. And, being the sort of advanced beginner type, I'm stuck. In this unit, we've learned to leverage local storage to persist data locally so we can get our favourite items even after the app is shut down. However, I have trouble getting that to work.
So here's what I've done:
The Failed Attempt
I can get data into local storage. And I can append data. I do this using this function:
$scope.favoriteData = $localStorage.getObject('favorites', '[]');
$scope.addFavorite = function (index) {
console.log('Current Favorites', $scope.favoriteData);
$scope.favoriteData = Object.keys($scope.favoriteData).map(function(k) { return $scope.favoriteData[k] });
console.log ($scope.favoriteData);
$scope.storeVar = $scope.favoriteData.push("'{id':" + index + '},');
console.log ($scope.favoriteData);
$localStorage.storeObject('favorites', $scope.favoriteData);
console.log('Added Favorite', $scope.favoriteData)
};
In local storage, this produces the following entry:
favorites: ["'{id':0},","'{id':1},"]
So far so good. However, this is useless. Because I need this object to have the following format:
favorites: [{'id':0}, {'id':1}]
and so on. Also, I should not be able to add duplicates. I have a kind of function for that elsewhere, but I am stuck on how to combine the two functions.
The function I have is this:
function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({
id: index
});
};
The problem with this is, I don't understand how it does what it does.
So please, help?
EDIT #1:
The Second Attempt
With the help of #Muli and #It-Z I'm working with the following code right now:
$scope.favoriteData = $localStorage.getObject('favorites', '[]');
$scope.addFavorite = function (index) {
console.log('Current Favorites', $scope.favoriteData);
$scope.favoriteData = Object.keys($scope.favoriteData).map(function(k) { return $scope.favoriteData[k] });
console.log ($scope.favoriteData);
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
console.log ("Found duplicate id " + favorites[i].id);
return;
}
}
$scope.storeVar = $scope.favoriteData.push({id: index});
console.log ($scope.favoriteData);
$localStorage.storeObject('favorites', $scope.favoriteData);
console.log('Added Favorite', $scope.favoriteData)
};
However, this doesn't work because with a nonexistant key favorites, it doesn't work and gives me an error. So I need to implement a check if the key exists and if it doesn't, then it should create one. I've looked at this question, but it didn't work, mainly because I must use the following factory in services.jsto access local storage:
.factory('$localStorage', ['$window', function ($window) {
return {
store: function (key, value) {
$window.localStorage[key] = value;
},
get: function (key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
storeObject: function (key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function (key, defaultValue) {
return JSON.parse($window.localStorage[key] || defaultValue);
}
}
}])
So this is where I'm at right now. And I'm still stuck. Or again stuck. I don't know.
$localStorage handles serialization and deserialization for you so there's no need for $scope.favoriteData = $localStorage.getObject('favorites', '[]');
You can just call:
$scope.favoriteData = $localStorage.favoriteData || {/*Defaults object*/};
Same goes for saving data. use the dot notation.
Check the demo.
As for the duplicates: just handle them yourself like you would normally. when you're done call $localStorage.mySet = modifiedSet (modified set is standard JS object).
Note: this assumes you use ngStorage.
First of all, this line:
$scope.storeVar = $scope.favoriteData.push("'{id':" + index + '},');
Should be:
$scope.storeVar = $scope.favoriteData.push({id: index});
This is because in the original line you are pushing string into favoriteData while you wanted objects.
And if you want to check first for duplicates your can go with somthing like this:
$scope.favoriteData = $localStorage.getObject('favorites', []);
$scope.addFavorite = function (index) {
console.log('Current Favorites', $scope.favoriteData);
$scope.favoriteData = Object.keys($scope.favoriteData).map(function(k) { return $scope.favoriteData[k] });
console.log ($scope.favoriteData);
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
console.log ("Found duplicate id " + favorites[i].id);
return;
}
}
$scope.storeVar = $scope.favoriteData.push({id: index});
console.log ($scope.favoriteData);
$localStorage.storeObject('favorites', $scope.favoriteData);
console.log('Added Favorite', $scope.favoriteData)
};

Fetching Data using .getJSON and storing using Knockout.JS

My TweetModel is setup like this
function TweetModel(tweet) {
var self = this;
this.tweet = ko.observable(tweet);
}
[UPDATED]
Running into trouble binding the solution. For some reason, after the TweetModel object is created, it is not being pushed to self.tweets.
I broke this up into steps...
.getJSON(someurl, function(data){
$.each(data, function (i, val) {
var tweetModel = new TweetModel();
tweetModel.tweet = data.key[0];
self.tweets.push(tweetModel);
//all could be compressed into self.tweets.push(new TweetModel(val));
//Object is being created but self.tweets returns an empty list when debugged
}}
Any help would be appreciated, thanks.
Try this:
$.getJSON(someurl, function (data) {
$.each(data.key, function (i, val) {
self.tweets.push(new TweetModel(val));
}
}

chrome.storage.sync.remove array doesn't work

I am making a small Chrome extension. I would like to use chrome.storage but I can't get it to delete multiple items (array) from storage. Single item removal works.
function clearNotes(symbol)
{
var toRemove = "{";
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
toRemove += "'" + index + "',";
});
if (toRemove.charAt(toRemove.length - 1) == ",") {
toRemove = toRemove.slice(0,- 1);
}
toRemove = "}";
alert(toRemove);
});
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value) {
alert(index);
});
});
});
};
Nothing seems to break but the last loop that alerts out what is in the storage still shows all the values I am trying to delete.
When you pass in a string to sync.remove, Chrome will attempt to remove the one single item whose key matches the input string. If you need to remove multiple items, use an array of key values.
Also, you should move your remove call to inside your get callback.
function clearNotes(symbol)
{
// CHANGE: array, not a string
var toRemove = [];
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
// CHANGE: add key to array
toRemove.push(index);
});
alert(toRemove);
// CHANGE: now inside callback
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
alert(index);
});
});
});
});
};
Slightly Slimmer and updated solution
chrome.storage.sync.get(null, (data) => {
const keys = Object.keys(data).filter((x) => x.startsWith('<start-of-key>')); // Can replace `startsWith` with regex or any other string comparison
chrome.storage.sync.remove(keys);
});

Show contents of localStorage into div

I have this basic function :
pid = 1;
$(function() {
if (localStorage["key"+pid] != null) {
var contentsOfDiv = localStorage.getItem("key"+pid);
$("#Div").html(contentsOfdDiv);
}
});
The problem is that the pid value will change eventually and I don't want to overwrite the contents of the key.
How can I proceed to stack every Div content that localStorage is saving for me ?
You can iterate on localStorage entries just like on any object properties :
for (var key in localStorage) {
console.log(key, localStorage[key]);
}
So your code could be :
$(function() {
var lines = [];
for (var key in localStorage) {
if (/^key/.test(key)) { // does the key start with "key"
lines.push(key.slice(3) + ' = ' + localStorage[key]);
}
}
$("#Div").html(lines.join('<br>'));
});
If I have understood well, you want to use pid to loop over the object.
Best way to do this and avoid for in chain prototypical problems is the following:
(I think for this case you are better with an array rather than with an object)
http://jsfiddle.net/hqkD9/
var localStorage = ['aaaa', 'bbbbb', 'cccc', 'dddd']; // don't forget to declare with var
var html_string = '';
$.each(localStorage, function(index, value) {
html_string += value + '<br>';
});
$('#my_div').html(html_string);

Categories

Resources