In .NET there is no out-of-the-box way of detecting if JavaScript is enabled from the server side (you can detect if JavaScript is supported, but the user could have disabled it). You can achieve this using several techniques. In this article I will explain how to achieve this using .NET's PageMethods.
PageMethods, as the name implies, are methods that belong to an ASP.NET page, but with a catch - they can be called from the client side as if they were part of a Web Service, but without having to actually build one.
A PageMethod must be a public static method and must be marked with the WebMethod attribute. Besides that, you need to a have a ScriptManager on the page with EnablePageMethods set to true.
This technique allows you to call server side methods from the client side without the burden of having to build a complete Web Service - .NET will do all the hard work behind the scenes.
The logic behind this solution is that JavaScript will be used to call a server side method that will store in a session variable a value indicating whether JavaScript is enabled. If JavaScript is not enabled, the method will never be called and so it is safe to assume that JavaScript is disabled.
This is all the code you need:
public class DetectJavascriptPage : System.Web.UI.Page {
protected const string JAVASCRIPT_ENABLED_KEY = "JavascriptEnabled";
public bool IsJavascriptEnabled { get { return GetJavascriptEnabled(); } }
protected override void OnPreRender( EventArgs e ) {
base.OnPreRender( e );
// Verify that the startup script isn't already registered (postbacks)
if (!this.ClientScript.IsStartupScriptRegistered("JavascriptTest_Startup"))
{
// Form the script to be registered at client side.
StringBuilder sb = new StringBuilder();
sb.Append("<script lang='javascript'>");
sb.Append("PageMethods.SetJavascriptEnabled(true, SetJavascriptOnSucceeded, SetJavascriptOnFailed);");
sb.Append("function SetJavascriptOnSucceeded() { }");
sb.Append("function SetJavascriptOnFailed(error) { }");
sb.Append("</script>");
// Register the startup script
this.ClientScript.RegisterStartupScript(typeof(JavascriptTest), "JavascriptTest_Startup", sb.ToString());
}
}
[WebMethod]
public static void SetJavascriptEnabled(bool enabled)
{
if (HttpContext.Current.Session[JAVASCRIPT_ENABLED_KEY] != null)
{
HttpContext.Current.Session[JAVASCRIPT_ENABLED_KEY] = enabled;
}
else
{
HttpContext.Current.Session.Add(JAVASCRIPT_ENABLED_KEY, enabled);
}
}
[WebMethod]
public static bool GetJavascriptEnabled()
{
if (HttpContext.Current.Session[JAVASCRIPT_ENABLED_KEY] != null)
{
return (bool)HttpContext.Current.Session[JAVASCRIPT_ENABLED_KEY];
}
return false;
}
}During pre render we will include JavaScript code to call the page method, which in turn will set a session variable. For knowing whether JavaScript is enabled or not, all you have to do is use the property IsJavascriptEnabled that was added to the page class.