简体   繁体   中英

Local storage JavaScript in HTML

I'm making a craft beer webpage, and I want users to type in their age before entering. The initial prompt works, but if I switch tabs and go back to home page I am prompted again.

Question: How do I only get one prompt and save it until user exits the whole webpage including navigating tabs.`

My script:

 <script> function CloseWindow(){ window.open('','_self',''); window.close(); } </script> <script> var age; age = prompt("Please enter in your age: "); if (age >= 21){ alert("Age is valid"); } else{ alert("Not valid age"); CloseWindow(); } </script> 

Use the window.localStorage object to store the user's age. This will allow the information to persist through pages.

if (window.localStorage && !window.localStorage.age) {
     //Your code here to prompt the user's age and save it in window.localStorage.age
} else {
    //Your code here to prompt the user's age and save it in document.cookie
}

Below is an example snippet on how you can incorporate localStorage by building on top of your code. You can clean it up for what you need. If you want an alternative that resets when you close your browser, you can just replace localStorage with sessionStorage .

 function CloseWindow() {
   window.open('', '_self', '');
   window.close();
 }

 var validAge = localStorage.getItem('validAge');
 if (!validAge) {
   var age;
   age = prompt('Please enter in your age: ');
   if (age >= 21) {
     alert('Age is valid');
     localStorage.setItem('validAge', 'true');
   } else {
     alert('Not valid age');
     localStorage.setItem('validAge', 'false');
     CloseWindow();
   }
 } else if (validAge === 'true') {
   alert('Age is valid');
 } else if (validAge === 'false') {
   alert('Not valid age');
   CloseWindow();
 }

This is a link that shows some localStorage polyfills for outdated browsers.

In order to do that, you need to create a variable in the local storage and check its content before running the whole function again. I suggest you check online for tutorials how to do that, here's one I found for you : http://diveintohtml5.info/storage.html

Here's an example of how to do it simply too :

//Get the variable from the local storage
var age = localStorage.getItem('age') || 0; //instead you get nothing

if (age >= 18) {
   //access the website
} else {
   //here's where you run your function
   //...

   //Set the local storage variable
   localstorage.setItem('age', age) //where *age* is the name of the function's variable

}

I hope this will helps ! Good luck ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM