Is it possible that the same name used can have many different values stored separately and to be shown in a list?
E.g.:
function save()
{
var inputfield = document.getElementById('field').innerHTML;
localStorage['justified'] = inputfield;
}
<input type="text" id="field" onclick="save();" />
Every time someone enters something in the input field, and click on save, the localstorage will only save the value in the same name, however, does this conflict the way storage are saved, like being replaced with the latest input value?
Also, is there any way to prevent clearing the localstorage when clearing the cache?
Actually localStorage 'should' be capable of storing integers, strings and arrays. I have been working on a notepad app using localStorage and save all my data using object literals:
var someData = {
withvars: "and values",
init: function() {
// not sure if this works but it should.
},
var1: {
subvar1: "data",
subvar2: "data2"
}
};
Then store it using JSON.stringify():
localStorage.setItem(varName, JSON.stringify(someData));
Then access it later with JSON.parse():
var dataBack = JSON.parse(localStorage.getItem("varName"));
If you always use object literals then you will have less trouble keeping track of how to store and how to retrieve data from localStorage.
No. You can store only one value in a localStorage entry.
There are two ways to store more values behind one keyword:
Use localStorage['justified_0'], localStorage['justified_1'] etcetera.
Store multiple values in an array and convert it to JSON before storing in localStorage['justified'] and convert it back to an array after reading.
Clearing the cache does not clear local storage.
This is something quite easily determined with a very simple test page. You can only store one value per key, and the values are not cleared when the cache is cleared. (I've just tried Firefox so far ...)
You can store a list of values in a single key by writing your own function to do it:
function addToPersistentList(listName, value) {
var val = localStorage[listName] || [];
val.push(value);
localStorage[listName] = val; // THIS DOES NOT WORK
}
edit oops it only supports stored strings; crap. OK well if you have json2 you'd do this:
function addToPersistentList(listName, value) {
var val = localStorage[listName] ? JSON.parse(localStorage[listName]) : [];
val.push(value.toString());
localStorage[listName] = JSON.stringify(val);
}
Of course this causes issues if you want to store dates etc.
Related
I currently save a bunch of objects (thousands) into the chrome.storage.local and then when on a specific web page checking whether specific IDs on the web page are in fact saved in local storage.
Here's a pseudo code
Bakcground script:
var storage = chrome.storage.local;
var json = '[{"kek1": {"aaa": "aaaValue", "bbb": "bbbValue", "ccc": "cccValue"}},{"kek2": {"ddd": "dddValue", "eee": "eeeValue", "fff": "fffValue"}}]';
var jsonParsed = JSON.parse(json);
jsonParsed.forEach(function(object) {
storage.set(object);
});
Content script (when on a specific page):
ids.forEach(function(id) {
storage.get(id, function(result){
if(!isEmpty(result)) {
//we found it, nice, now flag it as found
}
});
});
function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}
Which is easy and nice since I only have to do storage.get(id, ...
Unfortunately, I save a lot of stuff in storage, some of it I need to be removing periodically, which then becomes a hustle since I have to loop through all the objects and determining whether that particular object needs to be removed or it needs to remain.
So i decided I would do like these "parent object". Ie one object for settings, containing an array of objects with different settings the user would save. One object for the stuff that needs to be removed, containing an array objects. Etc
Like so - all relevant info that I want to remove periodically will be under one key "test" (temp name):
var json = '{"test":[{"kek1": {"aaa": "aaaValue", "bbb": "bbbValue", "ccc": "cccValue"}},{"kek2": {"ddd": "dddValue", "eee": "eeeValue", "fff": "fffValue"}}]}';
I know how to access the nested objects and their values:
var jsonParsed = JSON.parse(json);
jsonParsed.test[0].kek1.aaa
But I don't know how I would easily check for the keys saved in the storage since I would have to specify the "element number" ([i]).
Do I just do a for loop itterating over the array like so?
for (i = 0; i < jsonParsed.test.length; i++) {
var getKey = Object.keys(jsonParsed.test[i]);
if (getKey[0] == 'theKeyImLookingFor') {
//do stuff
}
}
To me that feels like non ideal solution since the for loop would have to run for each of the ids on the page and there could sometimes be close to 4000 of them. (4000 for loops back to back)
Is it a good idea to save a single object holding an array of thousands of other objects?
Am I doing it wrong or is this the way to go?
But I don't know how I would easily check for the keys saved in the storage
Use the standard Array methods like find or findIndex:
const i = arrayOfObjects.findIndex(o => 'someKey' in o);
Is it a good idea to save a single object holding an array of thousands of other objects?
It's a bad idea performance-wise.
What you probably need here is an additional value in the storage that would contain an array with ids of other values in the storage that need to be processed in some fashion e.g. expired/removed. It's basically like a database index so you would update it every time when writing an individual object. Since it contains only the ids, updating it is cheaper than rewriting the entire data.
Also, instead of performing lots of calls to the API, do just a single call:
// writing
chrome.storage.local.set(Object.assign({}, ...arrayOfObjects));
// reading
chrome.storage.local.get(arrayOfIds, data => {
for (const id of arrayOfIds) {
const value = data[id];
if (value !== undefined) {
// ok
}
}
});
How to write localStorage script which will remember the value of turning odometer...so that each time the user visits the site again , the odometer will resume on the value on which odometer was at when the user left the site? I'm beginner in javascript so please understand...
This is my code: https://jsfiddle.net/aht87opr/17/
I've found the following code which might help with my case: http://jsfiddle.net/Jonathan_Ironman/Hn7jc/
$('button').click(function() {
var mefedron = myOdometer.get();
$('#value').text(mefedron);
});
Nicely done on the odometer, looks good. Local storage is simple.
To set local storage:
localStorage.setItem("key", "value");
To get local storage:
var number = localStorage.getItem("key");
Be sure to try getting the local storage first so you can handle any null errors.
Get and Set
localStorage has a few ways to get and set values to the browser. The simplest is treating it like a regular object.
localStorage.distance = 55;
you can then retrieve the value by accessing the property name you created earlier.
console.log(localStorage.distance); // "55"
Strings are stored, parse the string
Notice that localStorage.distance was set as a number but when accessed was a string. If you only need to store a number you could pass the string through a function like parseInt().
console.log(parseInt(localStorage.distance)); // 55
Another solution is to use JSON
create an object model of your odometer.
var odometer = { distance: 55, timeForOilChange: false };
Then write to the localStorage passing your model through JSON.stringify
localStorage.odometer = JSON.stringify(odometer);
and read the value back out using JSON.parse
console.log(JSON.parse(localStorage.odometer));
// { distance: 55, timeForOilChange: false }
I have been trying to code in javascript where I want input given to be displayed on screen. I want to store the data from input in LocalStorage. I tried to take the value and using localStorage.setItem and localStorage.getItem I stored in local storage too. But as I want to display all the records I have inserted every time submit button has been clicked, I want to store current and previous records too.
I tried to push into an array but it had only current records and not previously stored values. I don't want jquery. I just want simple javascript code.
thank you.
eg-
var data=[];
function myFunction(data)
{
var name= document.getElementById("nm").value;
localStorage.name= name;
for(var i=0;i<localStorage.length;i++)
{
var key = localStorage.key(i);
var value = localStorage.getItem(key);
data.push( value);
}
}
Yep, as mentioned in the comments it is best to just store the String representation of your array and store it as a value in localstorage. Web localstorage lets you store simple key value pairs which can be integers or strings (mostly strings) official docs
You could do something like this:
var name= document.getElementById("nm").value;
var data;
if (localStorage.getItem("name") === null)
//First value to be stored
data = [];
else
//There is some value already in the array
data = JSON.parse(localStorage.getItem("name"));
//Push name to data array in any case
data.push(name);
//Update localStorage
localStorage.setItem("name",JSON.stringify(data));
I hope this gets you started in the right direction.
From what i understand, i'll have to save the array as a JSON file and then save that locally using HTML5 local storage. Does anyone have any examples so i can get my head around it. The tutorial showing up from Google don't seem very clear.
It can be quite straight-forward. Just put a delegate between your code and localStorage that converts all values from and to JSON:
// conversion functions
var fromJSON = JSON.parse,
toJSON = JSON.stringify;
// storage functions
var get = function(key) {
return fromJSON(localStorage[key]);
};
var set = function(key, value) {
localStorage[key] = toJSON(value);
};
Try CarboStorage. It handles objects automatically, including dates. Filtering is also supported.
http://carbogrid.com/index.php/storage/home
I'm trying to build a history list of clicked clicked page elements and store that list into HTML local storage, to be later displayed back to the user. The main pre-requisite is that the list cannot contain duplicates, so for example if the user clicks on item A and then on item B and again back on item A, only A and B are recorded. The third click is not recorded because it is not unique.
I'm also using persist.js.
I noticed that I am able to name the storage and give it a key and both are stored together in the real key of the localstorage thus: myStorageName>myKeyand my value is whatever I put there.
Here's the thing. I know you can store stringyfied JSON there but my list is built up from simple javascript variables one at at time.
I know what to do for the first click:
myStorageName.set(myKey, myCurrentElementId); // myCurrentElementId = this.id
now on the second click this is where I'm beginning to getting stuck. There is the original variable value already stored, now I want to append the new variable value. Assume that I can get the value from the store like this:
var dataExtract = myStorageName.get(myKey);
myObject = JSON.parse(dataExtract);
But how do I then turn this into a JSONstring -able thing (sorry I don't even know what it should be) that contains only a list of unique values. Does this make any sense to anyone?
First of all, you don't want to keep writing to/from localStorage everytime a link is clicked, because this'll slow down your page. Keep an updated Array populated with the element ids, then write to localStorage before the user navigates away from the page (by binding to the window's onbeforeunload event, for instance).
First:
var clickedLinks = []; // this Array will hold the ids of the clicked links
function uniqueClick(id){
return !~clickedLinks.indexOf(id); // this tests whether the id is already in the Array
};
In your click handler:
if(uniqueClick(this.id)){
clickedLinks.push(this.id); // append the new element id to the Array
}
Bind to window.onunload to save the Array before the user navigates from the page:
window.onunload = function(){
localStorage.setItem('clickedLinks',JSON.stringify(clickedLinks)); // stringify the Array and save to localStorage
}
To retrieve clickedLinks on subsequent page visit:
// convert the String back to an Array; try/catch used here in case the value in localStorage is modified and unable to be parsed, in which case clickedLinks will be initialized to an empty Array
try{
var clickedLinks = JSON.parse(localStorage.getItem('clickedLinks')) || [];
}catch(e){
var clickedLinks = [];
}
You may want to replace the first line (var clickedLinks = [];) with this last bit of code, as it will initialize the Array if it doesn't exist.
UPDATE:
IE8 does not support Array.indexOf. Alternatives might be:
use jQuery's $.inArray by replacing !~clickedLinks.indexOf(id); with !~$.inArray(id, clickedLinks);
Detect whether Array.prototype.indexOf is supported. If not, shim it with the code provided on this page.
Your model has an error. At the first time, you save a primitive value. Then, you want to "append" another value to it. Seems like you actually want to use an object:
var myObj = localStorage.getItem("myName");
if(myObj) myObj = JSON.parse(myObj); //Variable exists
else myObj = {}; //Elsem create a new object
function appendNewValue(name, value){
myObj[name] = value;
localStorage.setItem("myName", JSON.stringify(myObj));
/* Saves data immediately. Instead of saving every time, you can
also add this persistence feature to the `(before)unload` handler. */
}
I suggest to define in your code this:
localStorage.set= function(key,val)
{
localStorage.setItem(JSON.stringify(val));
}
localStorage.get = function(key,defval)
{
var val = localStorage.getItem(key);
if( typeof val == "undefined" ) return defval;
return JSON.parse(val);
}
and use them instead of get/setItem. They will give you ready to use JS values that you can use in the way you need.