Checking if JavaScript is Enabled

Websites increasingly rely on being able to control the end-user's browser environment via the JavaScript client-side programming language. While browsers without JavaScript support are a thing of the past, many security-conscious people choose to browse the web without JavaScript enabled in their browser for safety reasons. There are thus cases where it becomes necessary for the conscientious web developer to make sure the end-user's browser client has JavaScript enabled. In this short article, I discuss the easiest way to do this.

One notable feature of browsers that have JavaScript disabled is that they do not, in fact, execute JavaScript code (surprise, surprise!). This fact can be used to determine whether JavaScript is enabled. Pressing the button below will redirect you to a URL that tells you whether your browser has JavaScript enabled:

How is this functionality implemented? Take the following piece of JavaScript code. This function, if it is in fact executed at all, indicates that JavaScript is enabled -- it notifies the end user and redirects him to a CGI script that receives the status of JavaScript via a query string parameter.

<script type="text/javascript" language="JavaScript">
function CheckForJavaScript ()
    // control flow never reaches the form.
    //  instead we redirect to the CGI script 
    // with 'status' parameter: enabled

    return false;

Now, we call this JavaScript function from the form below. When the submit button of the form is pressed, the onClick handler calls our function if JavaScript is enabled. If not, the form is submitted with a form CGI parameter indicating that JavaScript is disabled:

<form action="/cgi-bin/" method="POST">
    <input type="hidden" name="status" value="disabled">
    <input type="submit" value="Check for JavaScript"  
    onClick="return CheckForJavaScript()">

Finally, the CGI script that handles the submission of the form contains the following code:

#!/usr/bin/perl -w

use strict;
use CGI;
my $cgi = new CGI;

# The 'status' cgi parameter tells
# us whether javascript was enabled

print "Content-Type: text/html\n\n";
print "<html><body><center><strong>\n";
print "You have Javascript " . $cgi->param('status');
print "</strong></center></body></html>\n";


While this example may seem needlessly elaborate, it demonstrates the easiest way to determine whether JavaScript is enabled. Basically, you want some non-JavaScript method of directing the end-user to page A (the no-JavaScript page), supplemented by a JavaScript handler that directs end-user to page B (the JavaScript page).

Ideally, your website should never depend on JavaScript -- it should only use it to supplement functionality or make things easier. Drop-down menus and other fancy goodies may be fun, but they detract from the usability of your website if they make it inaccessible to security-conscious people.