How can I display a Javascript prompt once on website load? - javascript

I have a javascript prompt that executes when I open my website for the first time. The basic function of this prompt is to ask the user for their name, and then insert it into a header I.E. "Hello, 'user'!" I have multiple pages on my website, and whenever I navigate to a different page and then navigate back to the home page, the prompt is displayed again, asking the user the same question over and over. Is there any way to have the prompt display only once on the first load of the website, and then keep the user's name in a variable until they close the website?
Here is my javascript:
function askName() {
let username = prompt("To make your time on this website better, please enter your name.");
if (username != null) {
document.getElementById("userpara").innerHTML = "Hello, " + username;
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}
}
And here is my Html:
<h1 id="userpara" style="text-align: center;"></h1>
<h1 id="noUser" style="text-align: center;"></h1>
To execute the function on page load, I used the onload function in the body tag in html like this:
<body onload="askname()">
...
</body>
Feel free to correct me on any of my code as well, since I'm still learning :)

Try using sessionStorage:
function askName() {
let username = sessionStorage.getItem('username');
if (username === null) {
username = prompt("To make your time on this website better, please enter your name.");
}
if (username != null) {
document.getElementById("userpara").innerHTML = "Hello, " + username;
sessionStorage.setItem('username', username);
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}
}
sessionStorage is different from localStorage in that sessionStorage is wiped whenever you close the window/tab, which is what you want. localStorage stays until a user clears the cache or you remove the data through script.

There are a variety of ways to persistently store information on a client's web browser:
Cookies
Sends the information to the web server.
Used for a tiny amount of data
Can be inconvenient to work with, usually requires some parsing.
Data can persist upon closing the web browser, or it can be automatically deleted when it closes, by using a session cookie.
localStorage/sessionStorage
Information stays on the client, doesn't automatically get sent to the web server
Easy to work with
Generally used with a small amount of data
sessionStorage data gets deleted upon closing the browser, while localStorage data persists
a new instance of sessionStorage data is created when a new tab or window is opened, so other tabs/windows can't access the same sessionStorage data
IndexedDB
Information stays on the client, doesn't automatically get sent to the web server
Allows storing large amounts of data
Works asynchronously
Complicated to use
Data persists upon closing the browser
Probably the easiest way to do this is by using localStorage:
function askName() {
let username = localStorage.getItem('username');
if (!username) {
username = prompt("To make your time on this website better, please enter your name.");
}
if (username != null) {
document.getElementById("userpara").innerHTML = "Hello, " + username;
localStorage.setItem('username', username);
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}
}
Note that the information doesn't get cleared upon closing the browser (probably the closest thing to do that is a session cookie, but it comes with the concerns of using cookies). Alternatively you can just use sessionStorage, if you don't need other tabs/windows accessing the same data.

save the value to localStorage and check next time if value there in localStorage
function askName() {
var user=localStorage.getItem('Username');
if(user){
document.getElementById("userpara").innerHTML = "Hello, " + user;
}
else{
let username = prompt("To make your time on this website better, please enter your name."); if (username != null) {
user=localStorage.setItem('Username', username)
document.getElementById("userpara").innerHTML = "Hello, " + username;
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}} }

Related

How to update value instead of restarting the app

I have this piece of code in my iOS app inside WebViewController.swift:
var pushIDOneSignal = userID
if pushIDOneSignal == nil
{
// do nothing
}
else
{
webviewurl += pushIDOneSignal! //Add PushID token to the URL
}
I'm using pushIDOneSignal to get the playerid for the user. The problem is when the user opens the app the first time, we get a nil value; because has to accept permission notifications first.
Somehow I managed to create a way to get the playerid, but it only works if the user accepts the notifications and then, closes the app, and opens again.
How can I make the app try to read this again: if pushIDOneSignal == nil after the user has accepted notifications? Then that time, will get the else condition and then we will get the playerid.
Edit:
I have idea-
if pushIDOneSignal == nil
{
// do nothing
}
else
{
webviewurl += pushIDOneSignal! //Add PushID token to the URL
}
How i can make keeps looping when value is nil? Thanks.

Keep user after redirect with firebase

Im currently working on a side project with firebase on web and it uses user auth. I have the user logging in and then creating a game room which redirects to a separate page for the game "room". After the page redirects though i cannot pull any of the users data and the only way that im doing it is by re initializing firebase and using
auth.onAuthStateChanged(function(user) {
if (user && user != null) {
uid = user.uid;
email = user.email;
currUser = user;
} else {
//user isnt logged in
window.location.href = 'index.html';
}
There seems to probably be an easier way to do this but i cant seem to get it working and this way also messes up sections of my other code.
Attaching an onAuthStateChanged callback is the idiomatic way to get the user.
You can also get the user with firebase.auth().currentUser. But if a token refresh is required, you may in that case mis-detect that there is no user. That why an onAuthStateChanged callback is recommended.
See the Firebase documentation on getting the current user.

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

JavaScript persist a search query through out the whole site

I'm currently fetching a query (e.g, http://localhost:49781/HTML/index.html?inputName=Marcus) from a html form using this following JavaScript:
function setSignedName() {
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
document.getElementById("signed_in_name").innerHTML += split[1];
} else {
document.getElementById("signed_in_name").innerHTML = "Not signed in";
}
running the script will get the result: Marcus.
I want this string to be persisted through out my site, so when the user navigates to another page the inputName will still be Marcus.
What is the best way of achieving this?
Edit: This approach is only for display/non-production use, I know using a server side language like PHP is the best approach.
I believe the best way is using localStorage. It works in all major browsers and it's easy to use:
function setSignedName() {
var userName = "";
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
userName += split[1];
} else {
userName = "Not signed in";
}
document.getElementById("signed_in_name").innerHTML = userName;
localStorage.setItem("userName", userName);
}
To access it:
var userName = localStorage.getItem("userName");
And this is it. Check for it in the Resources tab in Developer tools(F12) in your fav broswer.
You'll want to either repopulate it through GET parameters in your server side language, or if you want to hack it together, use a cookie and repopulate it with JavaScript on page load with "pushState".
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState()_method

how to force redirect to login page in javascript

I am building a website where I want users to have to log in to be able to view a certin page (kn this case it is called gallery.php) I implemented some code I found on this site, which redirects the user back to the login page when they click on the gallery link in the menu. However when I log in, and get redirected to the gallery again, the website does not acknowledge that I have logged in and redirects me back to the login page again. I am aware that questions like this have been asked before, but any help would be appreciated. My code is bellow
//from login.html
<!--//
/*This Script allows people to enter by using a form that asks for a
UserID and Password*/
function pasuser(form) {
if (form.id.value=="Admin") {
if (form.pass.value=="rycbar123") {
var sessionTimeout = 1; //hours
var loginDuration = new Date();
loginDuration.setTime(loginDuration.getTime()+(sessionTimeout*60*60*1000));
document.cookie = "SistaDansenSession=Valid; "+loginDuration.toGMTString()+"; path=gallery.php";
location="gallery.php"
} else {
alert("Invalid Password")
}
} else { alert("Invalid UserID")
}
}
//from gallery.php
<!--force login code-->
<script type="text/javascript">
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1) {
alert("You must be logged in to view this page")
location.href = "login.html";
}
else {
alert("login succesful")
} </script>
Thanks so much
Try changing:
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1)
to
if (document.cookie.indexOf("SistaDansenSession") < 0)
When you set the cookie, you are setting the cookie attribute 'SistaDansenSession' equal to the value 'Valid'. In your original code, you are attempting to retrieve a cookie attribute 'SistaDansenSession=Valid', whereas the attribute you want to retrieve is just 'SistaDansenSession'. When the cookie is set, the attribute exists, so it will have an index that is >= 0. In that case, the redirect to the login does not occur - which I think is your desired behavior.

Categories