简体   繁体   English

每天JavaScript提示一次

[英]JavaScript prompt once per day

Hey I want to make a JavaScript prompt that appear once per day. 嘿,我想做一个每天出现一次的JavaScript提示。

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 您可以设置一天后过期的Cookie: 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. 请注意,以这种方式存储正确的密码是不安全的,因为任何人都可以看到源代码并查看正确的密码,更安全的方式是做一些服务器端的工作,例如Nodejs应用程序。 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 同样在此实现中,任何人都可以将isLoggedIn cookie设置为true并通过它获取,一种更安全的方法是将一些令牌设置为服务器可以验证以查看其是否过期的cookie,或者是否采用Nodejs路由,还有更多资源可以进行安全身份验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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