简体   繁体   中英

JavaScript prompt once per day

Hey I want to make a JavaScript prompt that appear once per day.

My actual code is:

<script>
var pass; var pass1="mypassword";
password=prompt('Please enter your password to view this page!',' ');
if (password==pass1)
    alert('Password Correct! Click OK to enter!');
else
{
window.location="http://mywebsite.com";
}
</script>

Using this code the prompt will appear at every refresh

You could set a cookie that expires after a day: https://www.w3schools.com/js/js_cookies.asp

Here is an example that modifies your code:

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function isLoggedIn() {
    if(getCookie("isLoggedIn") === "true") {
        return true;
    } else {
        return false;
    }
}

var pass1 = "mypassword";

if(isLoggedIn() === false) {
      var password = prompt('Please enter your password to view this page!',' ');
    if(password === pass1) {
        alert('Password Correct! Click OK to enter!');
        setCookie("isLoggedIn", "true", 1);
    } else {
        window.location.reload;
    }
}

Note, storing the correct password this way is insecure as anyone can see the source code and view the correct password, a more secure way would be to do something server side like a Nodejs app. Also in this implementation anyone can set the isLoggedIn cookie to true and get by it, a more secure way is to set some token as the cookie that the server can validate to see if it expired or not, or if you do go the Nodejs route, there are more resources to do secure authentication

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