localStorage not working in other host - javascript - javascript

I am developing a firefox addon. i use localStorage to save some data and retrieve.
function to check if it is available or not
if(!localStorage.getItem('font')) {
populateStorage();
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
if not then create
function populateStorage(){
localStorage.setItem('cname', name);
localStorage.setItem('font', 'Helvetica');
localStorage.setItem('image', 'myCat.png');
}
This is perfectly working localhost but if i visit other host like google.com and try to get i am getting error not found
if(!localStorage.getItem('font')) {
alert('Not found !!!!');
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
}
is there any way to fix this issue ? or am i doing it in wrong way ?

LocalStorage is intended to be accessible only from the same host. This allows different websites to have a different scope for their data, and also ensures that one website cannot access data from another website.
From MDN,
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
From: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
If you need to share data across different domains, you should use server-side persistence.

From what I've undestood local storage is not cross domain solution, so this behavior is correct.
What you need to do is fallow MDN solution. I've found something like this:
// define 2 objects
var monster = {
name: "Kraken",
tentacles: true,
eyeCount: 10
}
var kitten = {
name: "Moggy",
tentacles: false,
eyeCount: 2
}
// store the objects
browser.storage.local.set({kitten, monster})
.then(setItem, onError);
(code copied from MDN > JavaScript APIs > storage )
In this solution data will be pinned to browser/extension, not to domain. But be aware, that data still will be destroyed when user clear browser cache or something like 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

How do I set up a JSON data set that can be accessed offline?

I am trying to build a mobile application with multiple pages that users can use and navigate offline. It will have a search function to look for certain pages within itself. In previous questions I was told setting up JSON data sets is the best way to do this; however, every example or tutorial or book I read about JSON data sets and accessing them all have to do with come communication with a server and browser. How would I set up the JSON data set and set up the ability for users to interact with it or call in via to access the JSON data set offline? I just assume that it would be different than setting it up like the examples I've seen so far
You can use localStorage to store the JSON data in the browser.
Let's say you have a file on the server called data.json with the following content:
[{ "name":"Name1", "surname":"Surname1" },
{ "name":"Name2", "surname":"Surname2"},
{ "name":"Name3", "surname":"Surname3" },
{ "name":"Name4", "surname":"Surname4" }]
When a user access the mobile application for the first time you can make a call to the server,get the JSON data and store it in the browser using localStorage:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON("data.json", function (data) {
localStorage.setItem('users', JSON.stringify(data));
});
});
</script>
Google Chrome -> Resource -> Local Storage:
Now that your JSON object is stored locally you can retrieve it from local storage and use it in your application without connecting to the server.Just make sure you always do a null check to make sure the data still exists locally, if it doesn't you would need to initiate a server call:
var users = JSON.parse(localStorage.getItem('users'));
if (users != null) {
for (var i = 0; i < users.length; i++) {
alert(users[i].name + " " + users[i].surname);
}
}
You can use sqlite to save the data you already grabbed. So you can decide to grab the whole data again when the user is online or you only grab the new content:
https://developer.android.com/training/basics/data-storage/databases.html
Another possibility is to download your data as .json file and load it in your app. So you'll need the read and write permissions of users.

How to save things using Javascript

I am making a website where you can store financial things. Just for practise. Not to publice. So far I have making the part where you can add a new list. And fill in things. But of course if I refresh the page it will be gone. So how can I save the new made list?
You could store it in the Browser via a cookie or better, localStorage. But of course if the browser deletes the "personal data" or you use a different browser, the data is gone.
Normally you would set up a server (say, PHP) and save it in a database (e.g. MySQL), even if you use the application only on your own machine.
Try using cookies or WebStorage (localstorage or sessionstorage objects). And consider using HTTPS if you working with financial info
You could use Firebase. Works great if you're only doing small things.
Basically it allows you to store data online on their servers with the simple Firebase API.
Their tutorial should get you started:
Firebase 5 minute tutorial
I am very new to learning localstorage myself and since you said "storeing in the browser" , i guess the best comtemporary and hassle and hack free method is localstorage .
Here is a accordion i made which stores the state of the accordion(weather its open or closed).
FIDDLE HERE
JS ::
$(function () {
var initialCollapse = localStorage.collapse;
if (initialCollapse) initialCollapse = initialCollapse.split(",")
console.log(initialCollapse);
$(".collapse-headings>a").click(function () {
var div = $(this).parent();
div.toggleClass("close open");
$(".collapse-content", div).toggle("slow");
localStorage.collapse = $(".collapse-headings").map(function () {
return $(this).hasClass("open") ? "open" : "close"
}).get()
console.log(localStorage.collapse)
return false;
})
if (initialCollapse) {
$(".collapse-headings>a").each(function (i) {
var div = $(this).parent();
div.removeClass("close open").addClass(initialCollapse[i])
$(".collapse-content", div).toggle(initialCollapse[i] !== "close");
})
}
});
This might be a good starting point to understanding localstorge , but if you do a google search , you'll come across a ton of useful information such as cross browser compatibility and local storage limitation and fallbacks.

how to localhost saved values check using javascript

how to localhost saved values check using java script,Button on click based saving one value,after page refresh want to check check value save,How to check
Dear you can use SESSION variable for it. You can store checked checkbox value in an index on array and that array stored in Session Variable. So by this way you will get all checked values and can use anywhere.
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.
The data is stored in name/value pairs, and a web page can only access data stored by itself.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Example:
function getItem(key){
if (!hasLocalStorage || !key) return;
return localStorage.getItem(key);
}
function setItem(key, val){
if (!hasLocalStorage || !key) return;
localStorage.setItem(key, val);
}
function hasLocalStorage () {
return typeof window.localStorage !== 'undefined';
}
//to store an item
setItem("itemKey", "itemVal");
//to retrieve an (the above, in this case) item
var fetchItem = getItem("itemKey");
Did you try to store that value in cookies?

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