Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / Javascript

Check if JavaScript is Enabled

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Mar 2010CPOL1 min read 10.1K   3  
How to check if JavaScript is enabled

Most of the pages now rely heavily on JavaScript and without it, some would be worthless, like the client side validation, AJAX and even fancy effects. If you are a good developer by practice, you should be able to have a fallback procedure if JavaScript is disabled, this is good if you are the one who did the coding but a nightmare if you are just inheriting a set of codes from a developer before, you need to check all of his code and look for those who are using JavaScript and if there is no exception handling, then you have write against it.

I found an easy way of doing it by creating a webcontrol that checks whether the clients web browser has JavaScript enabled or disabled. When I find out that the JavaScript is disabled, I redirect the user to a Message Page telling him to enable JavaScript. I think this is the quickest way in dealing with the said scenario rather than doing some exception coding.

My code consists of 4 parts:

  1. CheckJS.ascx – This is the web control for checking JavaScript
  2. CheckJS.ascx.cs
  3. Default.apsx – This is the sample default page where CheckJS is used
  4. Default.aspx.cs

CheckJS.ascx

ASP.NET
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CheckJS.ascx.cs" 
    Inherits="CheckJavaScript" %>
<asp:HiddenField ID="hfClientJSEnabled" runat="server" Value="False" />

<script type="text/javascript">
 document.getElementById('<%= hfClientJSEnabled.ClientID %>').value = "True";
 if (document.getElementById('<%= hfClientJSEnabled.ClientID %>').value != 
    '<%= IsJSEnabled %>')
 {
 window.location.href = '<%= GetAppendedUrl(JavaScriptQueryParameter, JavaScriptEnabled) %>';
 }
</script>

CheckJS.ascx.cs

C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Text;

public partial class CheckJavaScript : System.Web.UI.UserControl
{
 protected static string JavaScriptQueryParameter = "jse";
 protected static string JavaScriptEnabled = "1";
 protected static string JavaScriptDisabled = "0";

 protected override void OnInit(EventArgs e)
 {
 base.OnInit(e);
 bool bTestJS = IsJavaScriptEnabled;
 if (Request.QueryString[JavaScriptQueryParameter] != null)
 {
 IsJavaScriptEnabled = Request.QueryString[JavaScriptQueryParameter] == 
     JavaScriptEnabled;
 }
 }

 protected void Page_Load(object sender, EventArgs e)
 {

 }
 protected string GetAppendedUrl(string sNewParameter, string sNewParameterValue)
 {
 string sTargetURL = string.Empty;
 Uri oURL = (string.IsNullOrEmpty(ResolveUrl(NonJavaScriptTargetURL))) ? new Uri(
     ResolveUrl(JavaScriptTargetURL)) : new Uri(ResolveUrl(NonJavaScriptTargetURL));
 if (oURL == null)
 {
 oURL = Request.Url;
 }

 string[] aQry = oURL.Query.Replace("?", "").Split('&');

 StringBuilder oStringBuilder = new StringBuilder();
 if (aQry.Length > 1)
 {
 foreach (string sURL in aQry)
 {
 if (!sURL.ToLower().Contains(sNewParameter.ToLower()))
 {
 oStringBuilder.Append(sURL + "&");
 }
 }
 }

 if (oStringBuilder.Length > 0)
 {
 oStringBuilder.Remove(oStringBuilder.Length - 1, 1);
 sTargetURL = string.Format("{0}?{1}&{2}={3}", oURL.AbsolutePath,
     oStringBuilder.ToString(), sNewParameter, sNewParameterValue);
 }
 else
 {
 sTargetURL = string.Format("{0}?{1}={2}", oURL.AbsolutePath, sNewParameter,
     sNewParameterValue);
 }
 return sTargetURL;
 }
 protected override void OnPreRender(EventArgs e)
 {
 base.OnPreRender(e);
 if (IsJavaScriptEnabled)
 {
 string sTargetURL = GetAppendedUrl(JavaScriptQueryParameter, JavaScriptDisabled);
 HtmlGenericControl oHTMLControl = new HtmlGenericControl("NoScript");
 oHTMLControl.InnerHtml = string.Format(
     "<meta http-equiv=REFRESH content=0;URL={0}>", sTargetURL);
 Page.Header.Controls.Add(oHTMLControl);
 }
 else
 {
 if (!string.IsNullOrEmpty(NonJavaScriptTargetURL))
 Response.Redirect(NonJavaScriptTargetURL);
 HtmlGenericControl oHTMLControl = new HtmlGenericControl("NoScript");
 oHTMLControl.InnerHtml = string.Empty;
 Page.Header.Controls.Add(oHTMLControl);
 }
 }
 protected bool IsJavaScriptEnabled
 {
 get
 {
 if (Session["JavaScript"] == null)
 {
 Session["JavaScript"] = true;
 }
 return (bool)Session["JavaScript"];
 }
 set
 {
 Session["JavaScript"] = value;
 }
 }
 protected string JavaScriptTargetURL
 {
 get
 {
 return Request.Url.ToString();
 }
 }
 public string NonJavaScriptTargetURL
 {
 get
 {
 return (ViewState["NonJavaScriptURL"] != null) ?
     ViewState["NonJavaScriptURL"].ToString() : string.Empty;
 }
 set
 {
 try
 {
 ViewState["NonJavaScriptURL"] = ResolveServerUrl(value, false);
 }
 catch
 {
 throw new ApplicationException("Invalid URL. '" + value + "'");
 }
 }
 }
 public string ResolveServerUrl(string sServerURL, bool bForceHTTPS)
 {
 if (sServerURL.IndexOf("://") > -1)
 {
 return sServerURL;
 }
 string newUrl = ResolveUrl(sServerURL);
 Uri oOriginalURI = HttpContext.Current.Request.Url;

 newUrl = (bForceHTTPS ? "https" : oOriginalURI.Scheme) +  "://" +
     oOriginalURI.Authority + newUrl;
 return newUrl;
 }
}

public class CheckJavaScriptHelper
{
 public static bool IsJavascriptEnabled
 {
 get
 {
 if (HttpContext.Current.Session["JavaScript"] == null)
 {
 HttpContext.Current.Session["JavaScript"] = true;
 }
 return (bool)HttpContext.Current.Session["JavaScript"];
 }
 }
}

Default.apsx

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>
<%@ Register Src="CheckJS.ascx" TagName="CheckJS" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <uc1:CheckJS ID="CheckJS1" runat="server" />
 <div>
 </div>
 </form>
</body>
</html>

Default.aspx.cs

C#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 if (CheckJavaScriptHelper.IsJavascriptEnabled)
 {
 Response.Redirect("Supported.aspx");
 }
 else
 {
 Response.Redirect("NotSupported.aspx");
 }
 }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
New Zealand New Zealand
http://nz.linkedin.com/in/macaalay
http://macaalay.com/

Comments and Discussions

 
-- There are no messages in this forum --