Can I save input data from popup.html in localStorage? - javascript

I am working on pretty simple extension. My popup.html has some radiobuttons, which represent set of predefined options for user. The problem is that logic of my content-script depends upon those options.
So, my question is:
let us assume I would attach a script to 'popup.html' (meeting Chrome CSP) that listens to any change in my radiobuttons selection and as soon as it happens does someting like .localstorage.setItem(key, value)? Would my content-script be able to get this value from local storage at appropriate moment?

Naturally, you can do that. Here two examples:
chrome.storage.local.set({'value': theValue}, function() {
// Notify that we saved.
message('Settings saved');
});
chrome.storage.local.get('value', function(obj) {
//Notify that we get the value.
message('Value is ' + obj.value);
});
Or you can use the sync storage:
chrome.storage.sync.set({'value': theValue}, function() {
// Notify that we saved.
message('Settings saved');
});
chrome.storage.sync.get('value', function(obj) {
//Notify that we get the value.
message('Value is ' + obj.value);
});
Here is the documentation.
The difference between chrome.storage and window.localStorage, is that you can use window.localStorage on every recent browser. Also on websites. The stored objects will be stored until the user close the browser.
You are building a Chrome extension, so I would recommend you to use the API that was make for that.

Related

Outlook add-in Storage for settings

I've been trying to use
Office.context.roamingSettings.set("keyVal", value)
Office.context.roamingSettings.get("keyVal")
To save in storage, but it only work for the current session.
Now I've been trying to the saveAsync. But it doesn't take parameters. So I wanna how it supposed to be used. And also if it keeps the data in all platforms for the user(OWA, mobile, and Desktop)
Office.context.roamingSettings.saveAsync(function (result) {
if (result.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`Action failed with message ${result.error.message}`);
} else {
console.log(`Settings saved with status: ${result.status}`);
}
});
During the lifetime of the session you can just use the set and get methods to work with the in-memory copy of the settings property bag.
When you want to persist the settings so that they are available the next time the add-in is used, use the saveAsync method to save the settings after calling the set method. For an example see this code snippet: https://github.com/OfficeDev/office-js-snippets/blob/main/samples/outlook/10-roaming-settings/roaming-settings.yaml

about local storage.getItem()

I'm a new learner for API, and I have a quesion about local storage. This is a code example from my javascript book:
if (Modernizr.localstorage) {
var txtUsername = document.getElementById('username');
var txtAnswer = document.getElementById('answer');
txtUsername.value = localStorage.getItem('username');
txtAnswer.value = localStorage.getItem('answer');
txtUsername.addEventListener('input', function () {
localStorage.setItem('username', txtUsername.value);
}, false);
txtAnswer.addEventListener('input', function () {
localStorage.setItem('answer', txtAnswer.value); }, false);
}
}
I want to ask why should we "localStorage.getItem()" part? Cause I think if user type their username, then we can get their names just from the variable "txtUsername" cause I thought it should be setItem first and then getItem. Thank you!
Local storage is used to store small amounts of data on the client side. What does your code ?!
For example: A user visited the site for the first time and complete the inputs, , the data stored in the local store. The user closed the browser. The next day he again went to the site to fill out the form again, and its data is already filled. Conveniently!
Also we can use local storage as js object
txtUsername.value = localStorage.getItem('username');
txtUsername.value = localStorage.username;
txtUsername.value = localStorage['username'];
The thing is, it works just as you said.
It's just, when person types data in the textbox he uses setItem - that what 'input' eventListener used for
Think of LocalStorage as of really light database that keeps data even when user closes the page
But since it can store data when page is closed, you want to show the content of it in the textbox - and that's why author uses 'getItem' on start

is localstorage also user specific by default?

I am storing some data in the local storage using
localstorage.setItem("key","value")
I understand that localstorage is browser specific, now will this value remain even after i login as different user (sharepoint) in the same browser?
as far as i know localStorage is persistent until user clears it
and i read in this SO question that
Duration
In DOM Storage it is not possible to specify an expiration period for
any of your data. All expiration rules are left up to the user. In the
case of Mozilla, most of those rules are inherited from the
Cookie-related expiration rules. Because of this you can probably
expect most of your DOM Storage data to last at least for a meaningful
amount of time.
So does this mean that local storage is only browser specific? ie even if login as different user in sharepoint, the localstorage values will still remain if i use the same browser? (given that i dont clear it in log out/log in actions in sharepoint)
I understand that localstorage is browser specific, now will this value remain even after i login as different user in the same browser?
Yes.
Definitely.
It has nothing to do with php sessions or the like. Nothing.
LocalStorage is attached to the browser. Log in or log out, has no effect on localStorage.
even if login as different user, the localstorage values will still remain if i use the same browser?
Yes.
You can wrap browser storage with your own interface. It can have expiration by setting a timestamp on writes and checking it on reads.
var Storage = {
get: function (key) {
var item = localStorage.getItem(key)
if (item) {
var entry = JSON.parse(item)
if (entry.expires && Date.now() > entry.expires) {
localStorage.removeItem(key)
} else {
return entry.data
}
}
},
set: function (key, value, expires) {
var entry = { data: value }
if (expires) { entry.expires = expires }
var item = JSON.stringify(entry)
localStorage.setItem(key, item)
},
}

Web app data storage

Let's say I have two or more tabs with a couple of inputs and textareas.
Users can fill these fields and switch tabs but I want to make sure they don't lose the data in the fields.
Here comes the question: how would you save the data when the users switch between tabs?
Now I solved this problem by storing the data in variables, specifically in object literal (Javascript), but it is such a mechanical way to do it.
Of course I could push the data in a database.
I am using Javascript plus jQuery. I would really like to think of a good way to solve this kind of problem.
You can use localStorage.
Just set the values you want to store by:
localStorage.setItem(key, stringData);
To get the data:
var stringData = localStorage.getItem(key);
To delete:
localStorage.removeItem(key);
That way the data is stored locally in the user's browser. User can also come back later and data will still be there.
You can synchronize the tabs by listening the storage event:
window.addEventListener('storage', updateStorage, false);
function updateStorage(e) {
if (e.newValue === null) {
localStorage.removeItem(e.key);
} else {
localStorage.setItem(e.key, e.newValue);
}
}
The storageevent is only throw to the inactive tabs so they can update the isolated copy of the localStorage.
If you only need to store the data for a session you can use sessionStorage instead.
For more on localStorage:
http://www.w3.org/TR/2013/PR-webstorage-20130409/

What's the best way use caching data in js on client side?

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}

Categories