Coolnerds Hidden JavaScript Password Thang

It's pretty near impossible to hide JavaScript source code from all prying eyes. The reason being that, like HTML, JavaScript code is stored in text files that are downloaded to the user's computer. In other words, by the time the script is executed, it's already on the user's PC! You can, however, keep source code hidden from less-sophisticated eyes by using src= in your <script> tag.

Example

This page illustrates using hidden JavaScript code to set up a simple password-protection scheme. You can't get to the page named hidden02.htm until you've typed in the correct password and clicked the button. Viewing the document source of this page won't display the password in an obvious manner:

Type the password to go to hidden02.htm... 

Obviously, you can't test for the correct password unless you're able to find it, or I just tell you. The latter option is easier, so I'll tell you. The password is yowsa.

The HTML for the password form looks like this:

<form NAME="pform">
  <p>Type the password to go to hidden02.htm...&nbsp; 
  <input TYPE="Password" NAME="pword" size="20">
  <p><center>
  <input TYPE="button" VALUE="Then click me" onclick="checkWord()">
  </center></p>
</form>

As you can see in the HTML, when the user clicks the button, a function named checkWord() is called. That function checks displays an "access denied" message if the user typed the wrong the password. Or passes the user onto hidden02.htm if the password is correct. When you view the source for this page, you can't see the checkWord() function because it's in a separate file named hidden.js. But here are the contents of that hiddenjs.htm file:

//Position cursor to text field.
document.pform.pword.focus()

//Function to check password.
function checkWord() {
  //If you remove .toUpperCase() from line below, visitor must type
  //password n all uppercase letters, or it won't be accepted.
  if (document.pform.pword.value.toUpperCase() == "YOWSA") {
    location.href="hidden02.htm" 
  }else{
    alert ("Bad password, access denied!!!")
  }
}

The script doesn't require <script>...</script> tags, because they are already in this page, in this line which is down near the bottom of the page:

<script src="hidden.js" language="JavaScript"></script>

This password protection is weak. A sophisticated user can just browse directly to the hidden.js file to see its contents. Another downside to using src= in the <script> tag is that it's not supported by all web browsers. Unfortunately, the only way to handle password protection reliably is with CGI code and/or a database on the server side. Which, of course, complicates things tremendously.


Top  More JavaScript Examples  JavaScript Home Page  Coolnerds Home

 

Hit Counter