Introduction
I have been trying the whole of last week to figure out a way to detect if the client has JavaScript activated on his browser.
Background
I have found a rather useful method for the server side: Request.Browser.JavaScript
. This returns a boolean value indicating if the browser is capable of running JavaScript. The problem, however, is that the browser might be capable of running scripts, but it does not mean the user has turned it on yet.
I have tried many techniques, running the JavaScript in the header, changing the property of an HtmlItem
, etc., but couldn't get a true/false indicator on the server side, mainly because the server side executes before any JavaScript can change properties. And finally, last night, I thought of another way of doing it:
The Code
Everything is done in the code-behind page, and makes use of cleverly placed Session variables.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["JSChecked"] == null)
{
Session["JSChecked"] = "Checked";
Response.Write(@"<script language="'javascript'" type" +
@"='text/jscript'> window.location " +
@"= 'default.aspx?JScript=1'; </script>");
}
if (Request.QueryString["JScript"] != null)
{
Session["JsWorks"] = "True";
}
if (Session["JsWorks"] == null)
{
Session["JsWorks"] = "False";
}
if (Session["JsWorks"].ToString().Equals("False"))
{
}
else
{
}
}
This is a technique to run JavaScript using the code-behind. This will execute at the very top before the <html>
tags are loaded.
Response.Write(@"<script language="'javascript'" type='text/jscript'>" +
@" window.location = 'default.aspx?JScript=1'; </script>");
Points of Interest
The technique to run JavaScript in the code-behind can also be a very easy way of debugging your application if you use alert('');
methods within the script tag.
Please view my new article on how to achieve this using the Script Manager and a PageMethod
call:
History
- Last update - 19/04/2007.