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)
{
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).