Click here to Skip to main content
15,892,804 members
Articles / Web Development / ASP.NET

Check if JavaScript is Enabled from Server-Side Using an User Control

Rate me:
Please Sign up or sign in to vote.
4.59/5 (27 votes)
28 May 2008CPOL4 min read 170.7K   2K   39  
An ASP.NET User Control which can check if Javascript is enabled in the user's browser, and either does postback to perform an alternate action from the server side, or redirects to a non-JavaScript page.
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 CheckJS : System.Web.UI.UserControl
{
    protected static string JSQRYPARAM = "jse";
    protected static string JSENABLED = "1";
    protected static string JSDISABLED = "0";

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        bool testJS = IsJSEnabled;
        if (Request.QueryString[JSQRYPARAM] != null)
        {
            IsJSEnabled = Request.QueryString[JSQRYPARAM] == JSENABLED;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected string GetAppendedUrl(string newParam, string newParamValue)
    {
        string targeturl = string.Empty;
        Uri url = (string.IsNullOrEmpty(ResolveUrl(NonJSTargetURL))) ? new Uri(ResolveUrl(JSTargetURL)) : new Uri(ResolveUrl(NonJSTargetURL));
        if (url == null)
            url = Request.Url;

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

        StringBuilder sb = new StringBuilder();
        foreach (string s in qry)
        {
            if (!s.ToLower().Contains(newParam.ToLower()))
            {
                sb.Append(s + "&");
            }
        }

        if (sb.Length > 0)
        {
            sb.Remove(sb.Length - 1, 1);
            targeturl = string.Format("{0}?{1}&{2}={3}", url.AbsolutePath, sb.ToString(), newParam, newParamValue);
        }
        else
        {
            targeturl = string.Format("{0}?{1}={2}", url.AbsolutePath, newParam, newParamValue);
        }
        return targeturl;
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (IsJSEnabled)
        {
            string targeturl = GetAppendedUrl(JSQRYPARAM, JSDISABLED);
            HtmlGenericControl ctrl = new HtmlGenericControl("NOSCRIPT");
            ctrl.InnerHtml = string.Format("<meta http-equiv=REFRESH content=0;URL={0}>", targeturl);
            Page.Header.Controls.Add(ctrl);
        }
        else
        {
            if (!string.IsNullOrEmpty(NonJSTargetURL))
                Response.Redirect(NonJSTargetURL);
            HtmlGenericControl ctrl = new HtmlGenericControl("NOSCRIPT");
            ctrl.InnerHtml = string.Empty;
            Page.Header.Controls.Add(ctrl);
        }
    }
    protected bool IsJSEnabled
    {
        get
        {
            if (Session["JS"] == null)
                Session["JS"] = true;

            return (bool)Session["JS"];
        }
        set
        {
            Session["JS"] = value;
        }
    }
    protected string JSTargetURL
    {
        get
        {
            return Request.Url.ToString();
        }
    }
    public string NonJSTargetURL
    {
        get
        {
            return (ViewState["NONJSURL"] != null) ? ViewState["NONJSURL"].ToString() : string.Empty;
        }
        set
        {
            try
            {
                ViewState["NONJSURL"] = ResolveServerUrl(value, false);
            }
            catch
            {
                throw new ApplicationException("Invalid URL. '" + value + "'");
            }
        }
    }
    public string ResolveServerUrl(string serverUrl, bool forceHttps)
    {
        if (serverUrl.IndexOf("://") > -1)

            return serverUrl;
        string newUrl = ResolveUrl(serverUrl);
        Uri originalUri = HttpContext.Current.Request.Url;

        newUrl = (forceHttps ? "https" : originalUri.Scheme) +

                 "://" + originalUri.Authority + newUrl;
        return newUrl;
    } 
}

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

            return (bool)HttpContext.Current.Session["JS"];
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Architect
United States United States
I have more than 9 years of experience in various Microsoft Technologies. I spend most of my working time in C#, ASP.NET, WCF, WPF, WF and LINQ.

Check My Profile


Comments and Discussions