Accessing localstorage immediately after setItem() - javascript

I'm trying to store arrays in localStorage on the clients browser for easy access of the content after the page has loaded, the arrays are pulled from a database.
My problem is that I can only use the local storage once the page has reloaded and it has reflected on the client, similar to this problem HERE with cookies.
I can't seem to find a solution to this. Any help would be appreciated
some code:
localStorage.setItem('owner', JSON.stringify(data));
var seat = JSON.parse(localStorage.getItem('owner'));

You could await for local storage to be set before accessing it
(async () => await localStorage.setItem('owner', JSON.stringify(data)))();
var seat = JSON.parse(localStorage.getItem('owner'));

Related

localStorage not working in other host - 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.

Using Promise for a function that is not called by JavaScript

I am using Google Sign-In and have the following problem:
sessionStorage.getItem('userEntity') returns null when I close the browser and open it again. It does not return null if I just reload the page.
The session will be set in this function:
// Signing in
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
// Store the entity object in sessionStorage where it will be accessible from all pages
let userEntity = {};
userEntity.id = profile.getId();
userEntity.name = profile.getName();
userEntity.img = profile.getImageUrl();
userEntity.email = profile.getImageUrl();
sessionStorage.setItem('userEntity',JSON.stringify(userEntity));
userIsLoggedOut.style.display = 'none';
userIsLoggedIn.style.display = 'flex';
document.querySelector('.user-img').setAttribute('src', userEntity.img);
}
I do not run this function in JavaScript. The following HTML will make it run:
<div class="g-signin2" data-onsuccess="onSignIn"></div>
Even if I put console.log(sessionStorage.getItem('userEntity')) after the function or on the bottom of my JavaScript, it still returns null.
I guess a solution would be using Promise but how can I use it if I don't run the function onSignIn() in JavaScript?
The data stored in SessionStorage are deleted when you close the tab or the browser, more details below:
https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
You can use localStorage instead to keep the data in the browser even if you close the tab or the browser, so change the following line:
sessionStorage.setItem('userEntity',JSON.stringify(userEntity));
by
localStorage.setItem('userEntity',JSON.stringify(userEntity));
But you have to take care about the security of the informations stored in the localStorage, you can deal with secure cookies if you need to store secure data client side.
You can copy item from sessionStorage to localStorage:
localStorage.setItem('userEntity', sessionStorage.getItem('userEntity'));
It will be persistent, so you can use it anytime:
localStorage.getItem('userEntity');

Save data from GET request as variable

I've got a simple axios GET request that is working with Azure directline 3.0. The GET request pulls back data and shows it in the console (as seen in the picture).
The data I want to save into a variable is the conversationId. I then want to use this variable with Axios Post in another JS file to post as part of the link e.g. let URL = "https://directline.botframework.com/v3/directline/conversations/"+convID"/activities". With convID being the variable I wish to create. Right now I am manually changing the convID with the new conversation ID, but I want to create a variable so I can place it in the post javascript file so it is automatic.enter image description here
There are various ways you can solve this problem. Easiest one being, exposing the data on a shared object window.convID = convID and then accessing it wherever required.
You could also look to make singleton objects, which can be instantiated only once and hence will share it's variables across the lifespan of the application.
axios.get(/* URL */).then(res => {
window.convID = res.data.conversationId;
});
You can save that variable value in LocalStorage. Something like this:
let routeToYourApi = '/api/conversations'; // or something like this...
axios.get(routeToYourApi).then((response) => {
let conversationId = response.data.conversationId; // not sure if data object from your image is directly nested inside response that you get from server, but you get the idea...
window.localStorage.setItem("convId", conversationId);
}) // here you can fetch your conversation id
Than you can access it anywhere in your app:
let conversationId = window.localStorage.getItem("convId");
... and eventually remove it from local storage:
window.localStorage.removeItem("convId")
Hope this will help you!

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?

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/

Categories