Password protect a web page using Javascript

By: Guru Singh  

In the below code, "Password" is the password and "protected.html" is the name of the password-protected page. (Substitute your own password and URL when you use this script.) If visitors enter the correct password, they will forward to "protected.html"; if they enter an incorrect password, they'll hit the page called "oops.html." 

This shouldn't be used as a substitute for true security, but it isn't bad in a pinch. It works nicely for, say, an area of your site reserved for family members only. 

If you do use this code to protect a page or directory, you might want to keep search engines from listing it. Place this tag in the HEAD section of your protected page: 

<meta name="robots" contents="noindex"> 

Of course, it's possible for someone clever enough to get the password right from the source code. So you should somehow make the 'View Source' option impossible. You can do so by disabling Right click using Javascript.

<script language="Javascript">
<!--
var password = prompt("Enter in the password")
if (password == "Password") {
alert("Welcome!")
location = "protected.html"
}
else {
location = "oops.html"
}
//-->
</script> 

 




Archived Comments

1. ThomasDix
View Tutorial          By: ThomasDix at 2017-04-20 18:19:49

2. JasonNix
View Tutorial          By: JasonNix at 2017-04-13 03:22:33

3. rt
View Tutorial          By: sdf at 2016-02-15 02:10:57

4. This is so laughable. Delete this page already, it's outdated and the script isn't secure at all.
View Tutorial          By: LOL at 2015-12-13 18:18:51

5. Dear lord. This is shit. Anyone can view source whether you disable right-clicking or not. Ever hear
View Tutorial          By: Dude at 2015-09-06 09:31:58

6. I used the script above, and it seems to work except for 1 problem...when I type in the password, a
View Tutorial          By: Michael at 2012-05-15 20:50:49

7. Hi there,
this doesnt work in IE7 or firefox?
If you disable the right click option, t

View Tutorial          By: Gerrard at 2009-10-17 15:19:24


Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial