Last updated on November 10th, 2024 at 03:39 pm

A straightforward code example is provided for implementing password protection on a web page using JavaScript. While it is relatively simple to create password-protected web pages with JavaScript, it is important to note that this method lacks security, as JavaScript operates on the client side and can be disabled at any moment, allowing unauthorized access. Additionally, a variable named “count” has been introduced; if it reaches a value of 4, no further prompts will appear, and the user will be redirected to the main page.

You can change these settings like password and max attempts by modifying these variables

//change to your password
var password = "iamlost"
//max attempts
var maxattempt = 4

The complete code will look like the one below.

<script type="text/javascript">
function passWord() {
var count = 1;
var pass1 = prompt('Please Enter Your Password',' ');
//change to your password
var password = "iamlost"
//max attempts
var maxattempt = 4

while (count < 4) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == password) {
alert('You Got it Right!');
window.open('theotherpage.html');
break;
}
count+=1;
var pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.','Give Me The Password');
}

if(count == maxattempt)
{
alert("Attempted 4 times")
}

}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area"  onClick="passWord()">
</FORM>
</CENTER></strong>

All you have to do is save the above script to a HTML file. Run the script, Click on the button which says Enter Protected Area and enter the password “iamlost“, If you have entered the correct password you will be taken to the URL “theotherpage.html” otherwise it will show Access denied and a maximum of 4 prompts will be displayed.
Keep in mind that you have to enable pop up permissions in browser since we are using window.open method. You can also try using window.location.href instead (if you don’t want that pop up permission to be shown)

window.location.href = "theotherpage.html";

Demo (We are using window.location.href instead of window.open)