Use JavaScript to protect a page (II)

Store the passwords in a script

This technique shows you how to create a page with a text-field to enter the password and a button to use. If the password is valid the protected page is loaded. If the user enters a non-valid password a message will be shown.

First, you must create a separate file that contains the script, including the valid passwords. I call this page password.js.

Source
function CheckIt() {
var cPassword = document.forms[0].password.value;
var cNextPage = "secret.html";

if (cPassword == "secret" ||
cPassword == "whisper") {
document.location.href = cNextPage;
} else {
alert('Wrong password, please try again');
}
}

Change the value of cNextPage to the address of the page you want to load. At the moment there are two valid passwords, "secret" and "whisper". If you need more just you can just add them to the condition. For instance, to add "something" as a valid password change the condition to this :

Source
if (cPassword == "secret" ||
cPassword == "whisper") ||
cPassword == "something") {
etc...

Then you need a HTML page that contains the fields to enter. This page contains a script tag that loads the previously defined file password.js.

Source
<HTML>
<HEAD>
<SCRIPT language="JavaScript" src="password.js"></SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter the password and push the button to enter the secret zone
<INPUT type="password" name="password">
<INPUT type="submit" value="Ok" onClick="CheckIt(); return false;">
</FORM>
</BODY></HTML>

The option to store the passwords in a separate file and load this through the SCRIPT tag doesn't work in Internet Explorer 3.0, because this browser doesn't support the SRC attribute. If you want to support this browser than you must put the contents of password.js in the HTML page. Of course this makes the passwords visible to someone looking at the source of the page!

Back to the FAQ main page
Statistics

  Copyright © 1996 - 2000 Rob Schlüter,   schluter@knoware.nl   (last updated 1999/03/01)