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.

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 :

if (cPassword == "secret" ||
cPassword == "whisper") ||
cPassword == "something") {

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.

<SCRIPT language="JavaScript" src="password.js"></SCRIPT>
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;">

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

  Copyright © 1996 - 1999 Rob Schlüter,   (last updated 1999/03/01)