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
Related
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');
Good Day!
Being new to SCORM, I was wondering how Storyline 360 handles its suspend data. Does it affect the how it handles suspend data based on the LMS that you are using?
I have a scene that will generate a certificate for the learners upon completion. It defaults to the name that the LMS has and will auto-fill the input when the timeline starts.
One of the requirements for this is when a user changes the input to whichever name they desire, it should be saved and be retrieved upon their next visit. I used SCORM Cloud as a test LMS. My observation is that, for each relaunch of the course, it doesn't retrieve the name that I inputted from the last session through SetVar() and GetVar() methods.
I found a work-around by using lmsAPI.SetDataChunk to set the name then used lmsAPI.GetDataChunk to retrieve it. It worked well and fine but when it was deployed in our LMS it still retrieves something but, it is gibberish.
This is what I currently have by getting DataChunk:
This code will check if there were any saved names from previous sessions through GetDataChunk()
var player = GetPlayer();
var student = lmsAPI.GetStudentName();
var suspenddata = lmsAPI.GetDataChunk();
var username= player.GetVar("userName");
var displayname = "!";
if(suspenddata){
console.log("suspenddata is:"+suspenddata);
username=suspenddata;
}
if(!username){
console.log("username is null, setting to: "+student);
username=student;
}
player.SetVar("userName",username);
if(username){
displayname=" "+username+"!";
}
player.SetVar("displayName",displayname);
player.SetVar("nameInput",username);
When the user decides to change their name it will be saved to the storyline variable via SetVar() and is also passed to SetDataChunk() as shown below
var player = GetPlayer();
var nameinput = player.GetVar("nameInput");
var username = player.GetVar("userName");
var displayname = "!";
if(nameinput){
console.log("nameinput is:"+nameinput);
username = nameinput;
displayname=" "+username+"!";
player.SetVar("displayName",displayname);
player.SetVar("userName",nameinput);
lmsAPI.SetDataChunk(username);
}else{
console.log("nameinput is null");
}
This code works well when I deployed it to SCORM Cloud but as I said before, it would retrieve gibberish when deployed to our own LMS. I haven't tried deploying a version of this where it won't use DataChunk but even then the Storyline variables should be saved to the suspend data when deployed to SCORM Cloud but it doesn't. I am at my wit's end so any help would be appreciated. Thanks!
I have used the 'prompt' method into asking for a character name. however i am wandering if i can save that data to then use again in different html documents, to use the characters name in context. I am currently using Javascript and would like to try and use that to solve this issue.
You can use localStorage to access the data input by user on another page (must be same origin).
var value = prompt('Please enter your name');
if (value) {
localStorage.setItem('username', value);
}
To get the saved data on another page, use:
localStorage.getItem('username');
Just assign a variable prompt function. The user input will be saved in this variable.
var saveMe = prompt('What time is it?')
console.log (saveMe)
If you want to store data and use them only locally you should maybe use the local storage, this allow you to save data into the user's browser. But you should know that old browsers do not support that.
Look at the W3School class about local storage.
Here is an example of how it works :
localStorage.setItem("userName", prompt('Your name'));
And then when you need to access it :
localStorage.getItem("lastname");
I have a web page with 3 elements where a user will enter a text value and then press a button. On submit, it will process and return some values to be populated in a table.
This part works fine.
Now if the user refreshes the page, all the data is gone and the 3 elements and the table looks empty.
I would like to do this. Catch the refresh event and store the 3 user entered values in a local storage and when the page is loading back up, I will send this back to the controller to populate the tables again.
Is this possible to do? I am pretty new to web development and am running out of ideas.
This is what I tried. And this doesn't work.
window.onbeforeunload = function() {
localStorage.setItem(name, $('#name_field').val());
localStorage.setItem(id, $('#id_field').val());
localStorage.setItem(pw, $('#pw_field').val());
alert("am here")
}
window.onload = function() {
var name= localStorage.getItem(name);
if (name != null) $('#name_field').val(name);
var id= localStorage.getItem(id);
if (id!= null) $('#id_field').val(id);
var pw= localStorage.getItem(pw);
if (pw!= null) $('#pw_field').val(pw);
}
I could never get the alert in window.onbeforeunload function to pop up.
You can store it everytime on the local storage(or event session storage, which I think its better in your case). Then everytime you look after that value on the storage. In case of any value found, you send it to the controller.
If it was me I would do as I said above, save your data into the sessionStorage(what means that the data will be lost if user closes the tab/browser):
var saveData = function()
{
var data =
{
id: $("#id_field").val(),
name: $("#name_field").val(),
pw: $("#pw_field").val()
};
sessionStorage.setItem("formValues", JSON.stringify(data));
}
Idk if your post is async or not. If its async, you can call that function on your successCallback, if it isn't async, call it on the submit event.
Then at ready event, you can read that data:
$(document).ready(function()
{
var data = sessionStorage.getItem("formValues");
// Check if there is any user data already saved
if (data)
{
data = JSON.parse(sessionStorage.getItem("formValues"));
$("#id_field").val(data.id);
$("#name_field").val(data.name);
$("#pw_field").val(data.pw);
}
});
I prefer to store a group of data in an object into a single key on the storage, that is why I use JSON to stringify and parse an object, because storage only accepts string types.
A simple advise: Don't - ever - store passwords, let the user type it. For security reasons.
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/