Retain multiple fileEntries with chrome filesystem API? - javascript

How can I retain multiple fileEntry objects to reuse when the user opens the app with the chrome filesystem API? I've tried to use arrays to store the file entries and it works fine up until I restart the app and can't use them. Instead of returning a fileEntry object the console returns an object object (this is after I used chrome.storage.local.set and chrome.storage.local.get to set and retrieve the entries once the user restarted the app.)

You cannot persist the actual file entries between sessions. You need to use chrome.fileSystem.retainEntry which will return an id, which you can store, and then use chrome.fileSystem.restoreEntry to regain access to the entry when the app is re-opened.

After a lot of back and forth, I figured out how to retain multiple fileEntries.
Here's the code for the people who need it.
//save
//'fileEntries' is an array that I made earlier where multiple entries were stored
var keep = [];
fileEntries.forEach(function(entry, index) {
//if it's empty or null, return nothing
//otherwise add the id to our empty array 'keep'
if (entry == null) {
//do nothing
} else {
keep[index] = chrome.fileSystem.retainEntry(entry);
}
});
chrome.storage.local.set({
retained: keep
});
//load
chrome.storage.local.get('retained', function(data) {
var retained = data.retained;
retained = retained.filter(function(d) {
return d
});
for (var i = 0; i < retained.length; i++) {
var tab = retained[i];
chrome.fileSystem.restoreEntry(tab, function(entry) {
fileEntries.push(entry);
});
}
});
And.... thats about it! When the loading function is done, the fileEntries array, has all the fileEntry objects!

Related

Storing and Retrieving User Input

How to store user input from multiple pages and retrieve/display back user data on another html page
I am making a voting system and I needed help storing my results. Currently using local storage in JavaScript. Please do not recommended using data base as the deadline for the project is in 4 days.
So the main problem is whenever a user enters his/her preferences for a candidate the preferences are directly stored on another html page, but as soon as the second user enters his/her preferences the preferences by the first candidate disappears and the preferences for the second candidate gets stored.
I need to store preferences from every user to the html page. I need a efficient way to store my results in.
My local storage code
//store//
localStorage.setItem("preference1", selection[i].value);
// retrieve //
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
document.getElementById('display').innerHTML += `${key}: ${value} <br>`;
}
This answer is covering how you can add multiple "sets" of data to local storage (it is not secure and only works for a single browser):
Build an object containing all of the preferences for the current user
Push these into an array that will be stored in local storage
When saving the array, use JSON.stringify to convert the array to a string
When retrieving the array (as a string), convert it back using JSON.parse
(As localstorage is not allowed inside stack snippets, check this identical JSFiddle to see it working)
// Keeping your key in a variable is generally good practice
// so it's easy to change and immune to typos
const localStorageKey = 'preferences'
function addNew() {
// Build an object containing all the prefernces for the current user
var preferences = {
a: 'A',
b: 'B',
c: 'C',
}
// Load the existing data
var existingData = load()
// Push the new users data to the data
existingData.push(preferences)
// Save the data
save(existingData)
}
function load() {
// Get the saved data from local storage
var existing = localStorage.getItem(localStorageKey)
if (existing) {
// If the data exists, parse it back into an array
existing = JSON.parse(existing)
} else {
// If this is the first time, create an empty array
existing = []
}
// Return the array with any previous data included
return existing
}
function save(data) {
// Save data to local storage, converting the JS array to a string first
localStorage.setItem(localStorageKey, JSON.stringify(data))
}
// Adding events to the example buttons
document.getElementById("example1").onclick = addNew
document.getElementById("example2").onclick = function() {
var currentSave = load()
console.log(currentSave)
}
<button id="example1">Add new users data</button>
<button id="example2">Print out currently saved data</button>

How to set Firebase snapshot data into array in sessionStorage

var db1 = firebase.firestore();//API firestore database
var docRef1 = db1.collection("SuccessTransaction");
var showSeat = docRef1.get().then(function(snapshot){
snapshot.forEach(function(doc){
if(doc.exists){
alert(doc.data().Seat);
sessionStorage.setItem("routeUnavailableSeat", JSON.stringify(doc.data().Seat));
}else{
alert("No such documet!");
}
});
}).catch(function(error){
alert("Error getting document!", error);
});
I had a problem with this kind of situation. My intention was to set my snapshot value and set it into sessionStorage. The problem is after the system run, it will replace the old data and replace the new data. How can I using array or other method in order to keep all my data in sessionStorage?
The local storage API (that session storage is based on) can only store string values. So to store your values as an array, you will need to encode the array in a string.
Aside from that, it's a matter of getting the current value, parsing it, and then adding it back into session storage:
if(doc.exists){
let value = sessionStorage.getItem("routeUnavailableSeat");
let seats = current ? JSON.parse(current) : [];
seats.push(doc.data().Seat)
sessionStorage.setItem("routeUnavailableSeat", seats);
}

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

Double associative array or 1(n) loop more efficient?

I'm working on a WebSocket server using NodeJS and I really need to be able to look up a "class" by both the socket and the id of the user.
So I'm trying to figure out what would be more efficient, and why.
var usersBySocket = {};
var usersById = {}
// ID is pulled from database in NetworkClient constructor.
server.on('connection', function(client) {
var networkClient = new NetworkClient(client);
usersBySocket[client] = networkClient;
usersById[networkClient.getId()] = networkClient;
});
// When needing to send a specific user some data
// based on his user id (IE: Messaging).
// usersById(...).send(...);
OR
var users = {}
server.on('connection', function(client) {
users[client] = new NetworkClient(socket);
});
function getUserById(id) {
for(var uid in users) {
if(uid == id) return users[uid];
}
return undefined;
}
// Then when I needto use it, call it like so:
// getUserById(..).getSocket().send(..);
I'm leaning towards the first option, but I'm not sure exactly how JavaScript handles storing the values, if each "associative array" stores by value and not by reference, it's a complete waste. I especially don't want obsessive memory copy.
Objects are stored by reference. But the first option is always going to use more memory for the usersById object.
The second option uses less memory, but you are trying to do a linear search to find the user with the right id, this is not efficient.

Making an Array Variable Global in JavaScript

I'm setting a an array variable to 0 on load of my javascript.
var postArray= new Array();
However, I used this array to hold my objects that I retrieve from localStorage. It works when I upload more blog posts that get entered into localStorage and displays. However, after I refresh the page this is called again as is an empty array and say I go to enter my 3rd blog post after i've refreshed, my localStorage is set to only having the contents of my postArray. Therefore, I'm clearing out my localStorage when I dont want to.
if you throw it into an if statement, postArray is undefined.
if (localStorage.getItem("posts") === null) {
var postArray = new Array();
}
I'm trying to make the postArray global at the start yet only create a new array when localStorage is empty.
You should just get the content from the localStorage, and if it's empty, then return an empty array.
For example.
var postArray= getPosts();
function getPosts() {
var posts = localStorage.getItem("posts");
return posts ? JSON.parse(posts) : [];
}
i think you should use document coockie instead of array !!
when page is load read the cookie content if it's empty "localStorage" then store the "whatEver you want" value on its ! this is better than arrays

Categories

Resources