Is it possible to protect JavaScript code from prying eyes? I am aware you can establish hidden frames and pass parameters to scripts running in them. What can I do to stop the 'educated' browser from typing the URL where the hidden frame is and copying the source code?
It is impossible to hide your JavaScript code from anyone who truly wants to see it. This is because in order for a script to run in a client's browser, it must be freely sent from the server to the browser. And if a browser can read it, so can a person. That's the bottom line.
This doesn't mean, however, that you can't make it difficult for others to read your scripts. If you can make the source of your script more trouble to obtain than it is worth, then you've got pretty good protection.
One effective technique is to put the script in an external file and reference the file from the document that uses it. For information on how to do this, see the article, "Using Scripts from Another File," available elsewhere on this web site.
Of course, a clever person can view your document's source and determine the URL of the external file. Armed with this information, he can download the script all by itself, outside of the script's document context, and view it. You can respond to this threat, however, by programming your web server to offer the script file only when it is being referenced in the context of authorized files, such as the web pages that actually import the script. Since HTTP requests contain information to identify the referring file, you can determine whether a user is downloading your script (a) just to look at it or (b) to run it within the authorized document context.
Of course, this method is far from foolproof because it is easy for a skillful hacker to falsify HTTP requests. But to do that, he will have to know much more about HTTP than most amateurs, and the hack will cost him a little more effort than it is worth.
Charlton Rose
29 August 1997