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');
Related
I need to be able to know which client is sending a request to the server through web-sockets and tell it apart from other clients. The solution is a client id but I don't know the best way to store it so that the client can send it along with every request.
client
var clientId = null;
if (response.method === "connect"){
clientId = response.clientId
}
You could wrap your code with an IIFE which remove the possibility to access variables in the global scope outside of the IIFE. So only the code that runs inside of this IIFE can access the clientId variable. But changing the clientId from, for example, the console wouldn't change a thing.
(function() {
// Put all of your code in this scope.
var clientId = null;
if (response.method === "connect"){
clientId = response.clientId
}
})();
If only overwriting the variable is a problem, then you could alternatively use the Web Storage API to save the id in the browser, either permanently or until the tab has been closed. So you could store it like in the example below.
if (response.method === "connect"){
sessionStorage.setItem('clientId', JSON.stringify(response.clientId));
}
And use clientId further down the script, or even in another script on the same page with the following lines:
var storedClientId = sessionStorage.getItem('clientId');
if (storedClientId !== null) { // Check if the id has been set.
var clientId = JSON.parse(storedClientId);
}
So the IIFE will make modification to your variables impossible outside of its own scope. And the Web Storage API will store your client id in the browser and not in a variable.
I have below scenario
Page 1 has a link, when user clicks on it, it gets navigated to portal page with page reload. So just before navigation, a JSON object is created
The size of this object comes around 4KB roughly.
Sample object
let obj = {
"date":"12/31/2018",
"year":"2019",
"zip":"93252",
"members":[
{
"sdf":true,
"age":21,
"fdssss":false,
"aaaa":false,
"fdss":null,
"fsdfsd":[
"ADULT"
]
},
{
"sdf":true,
"age":21,
"fdssss":false,
"aaaa":false,
"fdss":null,
"fsdfsd":[
"ADULT"
]
}
}
There is a back link from that portal page, on clicking page will be navigated back to Page 1 with a page reload.
So when the page is navigated back, I need the created JSON object back again. I need it only for that session or the data should be persistent even if the page is reloaded.
Do I have to use localStorage? If i store the object in localStorage, at what point i should clear the storage? How should I handle between different users?
Do I have to use sessionStorage? what will be the scope of the data availability
I'm using AWS service.
Q1:
you can have localStorage, and you should handle it at the code when first page loaded and you can delete it when user do signout or login, storage is about browser not user, if there are some users behind one computer at different times you must clear all data manually.
Q2:
you can also have sessionStorage, per tab and will be removed by closing browser.
in details:
This is depends on your scenario which means localStorage used for long time but sessionStorage used when you need to store something temporary.
but the important thing about sessionStorage is that it is exist per tab if you close tab and windows the sessionStorage completely removed, it used for critical data such as username and password whereas localStorage is used to shared data whole the browser.
localStorage has no expiration date, and it gets cleared only by code, or clearing the browser cache or locally stored data whereas sessionStorage object stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
at the end I suggest you to use localStorage because you may want to share that data whole the browser event after closing browser and you can store more data, in the other side there are limitation about them, when you are used storage you should handle them manually and take care.
suppose:
function removeStorage()
{
var obj = localStorage.getItem('obj');
if(obj !== null)
localStorage.removeItem('obj')
}
and in login or logout success action call removeStorage() and in Page1 load have something like below:
var obj = localStorage.getItem('obj');
if(obj !== null)
{
....
//show the obj in label or do what you want with it
...
}
How to stay logged in after refreshing the page if I have token stored in local storage.
-or-
How to after receiving token from server(due to successful login), redirect to www.mypage.com/welcome page, but server will send to me this page only if I identify yourself as verified.
import this import { tokenNotExpired } from 'angular2-jwt' and add this simple function
loggedIn() { return tokenNotExpired }, some function of rxjs was deprecated in angular 6, so I use rxjs-compat for backward compatibility. It solve the issue.
Also, check this https://github.com/auth0/angular2-jwt
I'm assuming you're just using vanilla JS here.
You can check if an item is in local storage by using the localStorage.getItem('yourItem') method and an if statement, which would look something like:
if (localStorage.getItem('yourItem') === null) {
// code to execute if the item isn't in local storage
} else {
// code to execute if the item is in local storage
window.location = //full url to redirect to
window.location can be used to send the user to another URL inside the else block if they have your item in their local storage.
No, you can't do it via local storage. That's why cookies exist.
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
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'));