Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Detect if JavaScript is enabled in ASPX

0.00/5 (No votes)
22 Feb 2008 1  
Check if the browser has JavaScript enabled in the Page_Load method.

Introduction

This code sample detects if the current browser currently has JavaScript enabled.

Background

I searched for a way to determine if the user's web browser was running JavaScript, but discovered most samples on the net only detected if the browser was capable of running JavaScript and which version of JavaScript the browser is able to run. It did nothing to detect (at least from C#) whether JavaScript was currently enabled.

Using the code

I finally found four tutorials which I have combined bits of into one simple block of code that can be run from the Page_Load() method to see if JavaScript is enabled on a client's web browser or not.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["JSChecked"] == null)
    //JSChecked -indicates if it tried to run the javascript version
    {
        // prevent infinite loop
        Session["JSChecked"] = "Checked";
        string path = Request.Url + "?JScript=1";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect", 
          "window.location.href='" + path + "';", true);
    }
    if (Request.QueryString["JScript"] == null)
        Response.Write("JavaScript is not enabled.");
    else
        Response.Write("JavaScript is enabled.");
}

Points of interest

The greatest difficulty was that most tutorials for this type of function on the web all recommend using the following code:

Response.Write(@"<script language="'javascript'" type='text/jscript'>" + 
               @"   window.location  = 'default.aspx?JScript=1'; </script>");

Unfortunately, this code does not work if the browser is Firefox. However, using the command:

Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect", 
           "window.location.href='default.aspx?JScript=1';", true); 

works for all browsers that I have tested (IE, Firefox, Safari, and Opera).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here