Last updated on February 17th, 2022 at 07:29 pm

How to protect a web page using Javascript

Here is a simple code on how to password protect a web page using JavaScript. It is easy to enable password protected web pages using JavaScript but keep in mind that it is not at all secure since JavaScript is client side language and it can be disabled at any time to gain access. I have also implemented a variable named count and if reaches 4 then there will no longer be any prompt and it goes back 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)

Leave a Reply

Your email address will not be published. Required fields are marked *