Click here to Skip to main content
12,349,363 members (69,225 online)
Click here to Skip to main content
Add your own
alternative version

Stats

47.7K views
401 downloads
22 bookmarked
Posted

How to Detect JavaScript Status on the Client Browser using Script Manager

, 13 Aug 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
THis article explains how to detect JavaScript status on the client browser using Script Manager.

Introduction

Figuring out if the client browser is capable of running JavaScript is easy (Request.Browser.JavaScript), but figuring out if the client has this feature turned on in his/her browser becomes a bit more tricky.

Background

I have experimented with numerous ways, and found this to be the most efficient (free) method of detecting JavaScript active status on the client browser.

Using the code

The code is available in the JSDetect.cs page (the page that will be doing the detection of the JavaScript status). I have added in comments to explain the behavior:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace JSDetect
{
    public partial class JSDetect : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //sets initial assumption of javascript status 0 = false
            Session["jsActive"] = 0;
            //Set the script manager to run the page method
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), 
              "JSDetect", "PageMethods.SetJSEnabled();", true);
            //Sets the meta refresh to redirect to refering
            //url 2 <-seconds; url <- url to go to 
            refreshCommand.Content = "2; url=" + 
               Request.QueryString["url"].ToString();
        }

        /// <summary>
        /// a Webmethod that is also marked as a script method
        /// so that it can be called from javascript
        /// </summary>
        [WebMethod]
        [System.Web.Script.Services.ScriptMethod()]
        public static void SetJSEnabled()
        {
            //Method called from javascript and sets the jsActive session to 1 = true
            HttpContext.Current.Session["jsActive"] = 1;
            HttpContext.Current.Response.Redirect(
              HttpContext.Current.Request.QueryString["url"].ToString());
              //move back to refering url
        }
    }
}

In the JSDetect.aspx page, there is a meta refresh tag in the header to redirect to the caller page if nothing has happened. The script manager added to the form tag needs to have the EnablePageMethods property set to true in order to run the Web Method.

<%@ Page Language="C#" AutoEventWireup="true" 
  CodeBehind="JSDetect.aspx.cs" Inherits="JSDetect.JSDetect" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title></title>
<meta id="refreshCommand" runat="server" 
   HTTP-EQUIV="REFRESH" content=""> 
</head>
<body>
    <form id="jsTest" runat="server">
    <asp:ScriptManager ID="smanjs" 
      runat="server" EnablePageMethods="true">
  
    </asp:ScriptManager>
    <div id="ContentDiv" runat="server">
    
    </div>
    </form>
</body>
</html>

Now, to call this page in your application page, as you can see, the session is being referenced. If it does not exist, it goes and does the check. This is good in the case of sessions timing out. Also, I added a bit to skip this step for search engines.

I made the method for detection public static with HttpContext classes to ease the movement of this method into an external library.

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;

namespace JSDetect
{
    public partial class _Default : System.Web.UI.Page
    {
        bool jsEnabled = false;
        //run anuder initial assumption that JS is disabled

        protected void Page_Load(object sender, EventArgs e)
        {
            jsEnabled = IsJavascriptActive();
            
            Response.Write("Javascript running in browser: " + jsEnabled);
        }
        /// <summary>
        /// Detects whether or not the browser has javascript enabled
        /// </summary>
        /// <returns>boolean indicating if javascript
        // is active on the client browser</returns>
        public static bool IsJavascriptActive()
        {
            bool active = false;
            HttpContext context = HttpContext.Current;
            if (!context.Request.Browser.Crawler)
            {
                if (context.Session["jsActive"] == null)
                {
                    context.Response.Redirect(ClientDomainName() + 
                      "/JSDetect.aspx?url=" + 
                      context.Request.Url.AbsoluteUri.ToString() + 
                      " ", true);
                }
                else
                {
                    if (context.Session["jsActive"].ToString().Equals("0"))
                    {
                        active = false;
                    }
                    else if (context.Session["jsActive"].ToString().Equals("1"))
                    {
                        active = true;
                    }
                }
                
            }
            return active;
        }
        /// <summary>
        /// Get the Domain name and port of the current URL
        /// </summary>
        /// <returns>Domain name and port</returns>
        public static string ClientDomainName()
        {
            string domainNameAndPort = 
              HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, 
              HttpContext.Current.Request.Url.AbsoluteUri.Length - 
              HttpContext.Current.Request.Url.PathAndQuery.Length);
            return domainNameAndPort;
        }
    }
}

Points of interest

I felt I could kick myself for not thinking of this before since I have done something very similar with AJAX. I had knowledge of Java / server calls after studying code from the Dropthings.com drag drop service.

This can also be embedded into your default page without using an additional page, but this was built with the purpose of reusing the method.

License

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

Share

About the Author

L Viljoen
Architect
South Africa South Africa
I am a Technical Lead / Architect working on wide array of different technologies and frameworks. I have 2 International Diploma's in Software Development and Information systems and is completing my Bsc in Mathematics and Computer Science.

My Interests and hobbies are robotics , AI, Game development and 3d modelling

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 3 Pin
AlluvialDeposit13-Aug-12 3:40
memberAlluvialDeposit13-Aug-12 3:40 
GeneralNo cookies... Pin
Martin E Betz5-Nov-09 1:20
memberMartin E Betz5-Nov-09 1:20 
GeneralRe: No cookies... Pin
Chona11715-Nov-09 1:55
memberChona11715-Nov-09 1:55 
GeneralError Pin
stormcandi26-Aug-09 12:34
memberstormcandi26-Aug-09 12:34 
GeneralRe: Error Pin
Chona117126-Aug-09 21:21
memberChona117126-Aug-09 21:21 
GeneralRe: Error Pin
stormcandi27-Aug-09 5:23
memberstormcandi27-Aug-09 5:23 
GeneralRe: Error Pin
stormcandi31-Aug-09 6:34
memberstormcandi31-Aug-09 6:34 
GeneralRe: Error Pin
Chona117131-Aug-09 9:42
memberChona117131-Aug-09 9:42 
AnswerRe: Error Pin
Chona117131-Aug-09 10:40
memberChona117131-Aug-09 10:40 
GeneralRe: Error Pin
stormcandi9-Sep-09 13:30
memberstormcandi9-Sep-09 13:30 
GeneralRe: Error Pin
Chona11719-Sep-09 20:05
memberChona11719-Sep-09 20:05 
GeneralRe: Error Pin
stormcandi1-Oct-09 6:14
memberstormcandi1-Oct-09 6:14 
QuestionBrowser differences Pin
Norbert Bietsch17-Apr-09 13:10
memberNorbert Bietsch17-Apr-09 13:10 
AnswerRe: Browser differences Pin
Chona117119-Apr-09 1:13
memberChona117119-Apr-09 1:13 
QuestionRequest.Browser.JavaScript troubles? Pin
kub_net13-Apr-09 21:33
memberkub_net13-Apr-09 21:33 
AnswerRe: Request.Browser.JavaScript troubles? Pin
Chona117113-Apr-09 21:56
memberChona117113-Apr-09 21:56 
AnswerRe: Request.Browser.JavaScript troubles? Pin
AlluvialDeposit13-Aug-12 3:37
memberAlluvialDeposit13-Aug-12 3:37 
General[My vote of 1] Not everyone is meant to write articles Pin
Nuri Kevenoglu13-Apr-09 11:38
memberNuri Kevenoglu13-Apr-09 11:38 
GeneralRe: [My vote of 1] Not everyone is meant to write articles Pin
Chona117113-Apr-09 20:42
memberChona117113-Apr-09 20:42 
QuestionRe: [My vote of 1] Not everyone is meant to write articles Pin
AlluvialDeposit13-Aug-12 3:39
memberAlluvialDeposit13-Aug-12 3:39 
QuestionWhat about Script/Noscript? Pin
spoodygoon13-Apr-09 9:37
memberspoodygoon13-Apr-09 9:37 
AnswerRe: What about Script/Noscript? Pin
Chona117113-Apr-09 20:47
memberChona117113-Apr-09 20:47 
GeneralRe: What about Script/Noscript? Pin
rarefy1-May-09 7:12
memberrarefy1-May-09 7:12 
GeneralRe: What about Script/Noscript? Pin
Chona11711-May-09 10:11
memberChona11711-May-09 10:11 
GeneralRe: What about Script/Noscript? Pin
Chona11711-May-09 10:17
memberChona11711-May-09 10:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160621.1 | Last Updated 13 Aug 2012
Article Copyright 2009 by L Viljoen
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid