Password protect a web page using Javascript

By: Guru Singh Emailed: 1790 times Printed: 2623 times    

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> 

 

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Hi there,
this doesnt work in IE7 or firefo

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

2. I used the script above, and it seems to work exce
View Tutorial          By: Michael at 2012-05-15 20:50:49

3. Dear lord. This is shit. Anyone can view source wh
View Tutorial          By: Dude at 2015-09-06 09:31:58

4. This is so laughable. Delete this page already, it
View Tutorial          By: LOL at 2015-12-13 18:18:51

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

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

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