Detect Javascript ASP.NET server control



The problem
I recently faced the problem of whether or not my ASP.NET web app's AJAX parts will run on the client browser. If not, I would like to offer some sort of alternative functionality. I was surprised to find that there were no ready-made javascript detection control for ASP.NET.

The solution
DetectJavaScript is a server control that a developer can embed to a web page. By default it does not have a visible user interface, but it can show the state of javascript detection to the user if needed. The main use case is to check programmatically from the control if JavaScript is enabled or not and act accordingly.

It has a few properties that control its functionality:
  • AutoPostBack, if true the form will be automatically posted back
  • JavaScriptDisabledText, shown if JavaScript is disabled
  • JavaScriptEnabledText, shown if JavaScript is enabled
  • JavaScriptNotYetDetectedText, shown if it is not yet known whether JavaScript is enabled (the form has not yet been posted back)

The control emits dynamically a small piece of JavaScript code to the browser that sets a hidden form field value and submits the form (if AutoPostBack==true). On the server side, if the hidden form field contains the value set by the JavaScript code, we know that JavaScript works on the browser. Note that this cannot be known unless the form has been submitted once (Postback in ASP.NET terminology) to the server. The state of JavaScript support is stored in the viewstate, so it is really checked only once per page.

The JavaScript support can be checked by examining either of these members:
  • State (of type DetectionState)
  • IsJavaScriptEnabled (of type boolean)

DetectionState is an enum that has the following values:
  • NotYetDetected, means that the page has not been posted back yet (AutoPostBack == false and the user has not manually posted it back, or javascript is indeed disabled)
  • JavaScriptEnabled, JavaScript support has been succesfully verified
  • JavaScriptDisabled, JavaScript support has been checked and the result is that it is disabled

Sample Site
The source code includes a sample test site with both a traditional ASP.NET WebForm page and a page that is based on a master page. There is a catch when using a master page (and the control in the master), you have to check DetectJavaScript outcome in the Page_LoadComplete() event handler. This is because in Page_Load() phase the master and its controls have not been loaded yet.
Last edited Sep 25 2007 at 6:06 AM by AaliAlikoski, version 7
Comments
No comments yet.

Updating...