Click here to Skip to main content
Click here to Skip to main content

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

By , 13 Aug 2012
 

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)

About the Author

Chona1171
Web Developer
South Africa South Africa
Hi I am a Software Developer, I have studied, Comprehensive programming, Software Development, Business and Project Management.
 
After my First year of studies I recieved a full bursary for my second year and worked as a Junior Software Development Instructor,
I am skilled in a vast array of languages my top languages being Java (SE,ME,EE),SQL C#, VB.Net, VB 6 & Asp.Net,

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 3memberAlluvialDeposit13-Aug-12 3:40 
There's to many bugs (as commented from others)
You really should finish this article and fix all the bugs (or potential bugs)
GeneralNo cookies...memberMartin E Betz5-Nov-09 1:20 
I Tried to disable cookies.
That made the page reload it self in an infinite loop...
GeneralRe: No cookies...memberChona11715-Nov-09 1:55 
Yes thats kinda a bugger at the moment since sessions do in fact use cookies [unless is coolieless, configured in teh web.config] , thus you have to ammend the code to rather keep the javascript state via a query string. if you want to cater for cookieless clients, mind you which is not the majority since everything nowadys use cookies anyways and turning it off simply messes up your internet experience in general
 
Chona1171
Web Developer (C#), Silverlight

GeneralErrormemberstormcandi26-Aug-09 12:34 
I have copied your code which is great but am getting this error when I try to run it.
 

Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'SetJSEnabled' failed with the following error: System.NullReferenceException-- Object reference not set to an instance of an object.
 
I cannot figure out how to fix it. Can you assist?
 
~Candi

GeneralRe: ErrormemberChona117126-Aug-09 21:21 
Hi I will check out the error, I know there are some issues when using operah browsers, mostly becuase operah does not support async postbacks.
 
Also whatch this space by saturday i am planning to upload a more efficient way to achieve this , by using the form Post method, that will work on operah browsers aswel.
 
Cheerz
 
Chona
 
Chona1171
Web Developer (C#), Silverlight

GeneralRe: Errormemberstormcandi27-Aug-09 5:23 
Chona,
 
Just so you know I am using IE not Opera. Thanks for looking into this.
 
~Candi

GeneralRe: Errormemberstormcandi31-Aug-09 6:34 
Chona,
 
Did you post a new version? If so I cannot find it.
 
~Candi

GeneralRe: ErrormemberChona117131-Aug-09 9:42 
sorry I have been flooded in a few project these last couple of days, but I am pleased to say the latest javascript detection library is in its final testing stages and will be available by end of tommorrow (need some time to document and format it properly to publish).
 
its much more efficient than using the service this time round.
 
Chona
Web Developer (C#), Silverlight

AnswerRe: ErrormemberChona117131-Aug-09 10:40 
ok maybe a bit earlier , cant sleep anyways. you'll find the latest example here .
 
<a href="http://www.codeproject.com/KB/aspnet/JSDetectionFormSubmit.aspx">Detect Javascript status of browser using Form Submit</a>[<a href="http://www.codeproject.com/KB/aspnet/JSDetectionFormSubmit.aspx" target="_blank" title="New Window">^</a>]
 
Goodluck and let me know how it goes.
 
Chona1171
Web Developer (C#), Silverlight

GeneralRe: Errormemberstormcandi9-Sep-09 13:30 
I get a message saying that the article is still being written and is not avaialble when I go to the link you posted.
 
~Candi

GeneralRe: ErrormemberChona11719-Sep-09 20:05 
Yes i have been contacted my code project that the article i posted will be seed content for their new section "Quick Tips", if you provide me with an email address, i will be glad to send it to you
 
Chona1171
Web Developer (C#), Silverlight

GeneralRe: Errormemberstormcandi1-Oct-09 6:14 
Chona,
 
I emailed you a few weeks ago with my email address? Did you receive it? I am waiting for your new code. Smile | :)
 
~Candi

QuestionBrowser differencesmemberNorbert Bietsch17-Apr-09 13:10 
Thanks for the nice article. I found it helpful with my first try on PageMethods.
However, it seems that there are differences between browsers whether PageMethods are run synchronously or not:
While IE7 and Firefox3 do work synchronously, Opera 9.6 obviously does not, meaning that Session["jsActive"] did not show what I expected Cry | :((
Another aspect that is interesting: How to use WebMethods with HttpWebRequests.[^]
Again, thank you.
AnswerRe: Browser differencesmemberChona117119-Apr-09 1:13 
Thank you I will be looking to find a workaround for this, also I found a piece of software on the net called Browserhawk which works perfectly for client browser capabilities detection if you are willing to lay down some cash
 
A while back I also used ajax to do this on the page running the webite , to make async call to the server on the page load to notify the server side that javascript is active. I have been trying to get this to run faster (eliminating the redirect round trip) but keep running into the problem that server side runs before any clientside code executes.
 
And thank you for the link posted, it is very important to secure your application when using these web methods, even if the WebMethod does not contain any code that can be used with malicious intent a script guru thats clever enough can queue up an insane amount of requests , so it will be well important to limit the request queue to keep your server from crashing check out , http://technet.microsoft.com/en-us/library/dd425294(office.13).aspx[^]
 
Thanks
 
Chona1171
Web Developer (C#), Silverlight

QuestionRequest.Browser.JavaScript troubles?memberkub_net13-Apr-09 21:33 
What type of troubles you figured out using HttpContext.Current.Request.Browser.JavaScript?
 

Best regards.
AnswerRe: Request.Browser.JavaScript troubles?memberChona117113-Apr-09 21:56 
The main fact that this only detects whether or not the client browser is capable of running javascript, but it does not detect if the client actually have javascript turned off or on on their browser
 
Le Roux Viljoen
Web Developer
PCW New Media
South African Branch
www.pcwnewmedia.com

AnswerRe: Request.Browser.JavaScript troubles?memberAlluvialDeposit13-Aug-12 3:37 
That's correct!
--------------------
When Chuck Norris' dreams come true, your worst nightmares begin.

General[My vote of 1] Not everyone is meant to write articlesmemberNuri Kevenoglu13-Apr-09 11:38 
You're trying to power a skateboard with jet engine. Off the top of my head, I can think of 3 ways to do the same thing in a much more efficient way. You should delete this article to save yourself some embarrassment.
GeneralRe: [My vote of 1] Not everyone is meant to write articlesmemberChona117113-Apr-09 20:42 
Since you are such a pro please explain to me , and the good people that use code project how this can be achieved in a simpler more efficient way.
 
Save yourself some embarrassment of being all show and no go and put your code where your mouth is.
 
Please note the solution is not as simple as using a script/noscript tag, this is actually to let the server side know that javascript is turned on in the client browser.
 
Le Roux Viljoen
Web Developer
PCW New Media
South African Branch
www.pcwnewmedia.com

QuestionRe: [My vote of 1] Not everyone is meant to write articlesmemberAlluvialDeposit13-Aug-12 3:39 
I can't say your comment is wrong without giving you a reason for it? Please shar your 3 other ways to do this..
--------------------
When Chuck Norris' dreams come true, your worst nightmares begin.

QuestionWhat about Script/Noscript?memberspoodygoon13-Apr-09 9:37 
Script/NoScript should work just fine for Javascript detection? Is there a reason that simple solution won't work?
AnswerRe: What about Script/Noscript?memberChona117113-Apr-09 20:47 
Oh why i didnt ever think of this wow ???? Poke tongue | ;-P
 
This is fine and well , but how do you tell the server side(code behind) that it is running scripts or noscript?
 
Lets say the scenario where you have ajax based navigation on your website , like one of my sites www.nwcf.co.uk , and for non javascript users (and search engines) that still need to be able to navigate your site while maintaining the layout of your site (Instead of just lumping in a noscript tag that contains links ).
 
Le Roux Viljoen
Web Developer
PCW New Media
South African Branch
www.pcwnewmedia.com

GeneralRe: What about Script/Noscript?memberrarefy1-May-09 7:12 
NoScript is not working on patched XP and Vista machines as of this month. I have serveral customers with this issue right now so am scrambling to find a new way to detect JavaScript turned on.
GeneralRe: What about Script/Noscript?memberChona11711-May-09 10:11 
Well the article above explains how yo can inform the server side if the client has javascript turned on, the only known limitation this has is on Operah browsers (because it does not support synchronous calls) it will always give you a javascript off result.
 
This is the second version of the javascript detection method i use, you can also check the first version (its a bit messy and can be cleaned up)
 
if you need a simpler solution here's what you do,
 
instead of using the noscript tag use div
like here an example:
 

This should display if javascript is off
 

 

<script language='javascript' type='text/javascript'>
//hide noscript
document.getElementById('noscript')style.display = 'none';
//show script enabled blocks
document.getElementById('displayifJSenabled').style.display = 'block';
 
</script>
 
now by default none javascript is followed and if the script is executed (meaning javascript is on) it gets hidden and the javascript content gets shown.
 
if you where using mainly just html this would be the new way to go as it does not effect the html doc size by much (factor when dealing with Search engine optimisation)
 
but if you are using a server side language its best to build these tags on the server side with the server side knowing that javascript is enabled. you can use my methods and if you are willing to lay down some cash , you can always get browserhawk , even though its a .net component it can also work on cold fusion (7 & 8) and asp.
 
Hope this helps.
 
Chona1171
Web Developer (C#), Silverlight

GeneralRe: What about Script/Noscript?memberChona11711-May-09 10:17 
Sorry about previous post didnt set the tags property rite
 
Well the article above explains how yo can inform the server side if the client has javascript turned on, the only known limitation this has is on Operah browsers (because it does not support synchronous calls) it will always give you a javascript off result.
 
This is the second version of the javascript detection method i use, you can also check the first version (its a bit messy and can be cleaned up)
 
if you need a simpler solution here's what you do,
 
instead of using the noscript tag use div
like here an example:
 
<div id='noscript' style='display:block'>
This should display if javascript is off
</div>
 
<div id='displayifJSenabled' style='display:none'>
This should display if javascript is on
</div>
 

<script language='javascript' type='text/javascript'>
//hide noscript
document.getElementById('noscript')style.display = 'none';
//show script enabled blocks
document.getElementById('displayifJSenabled').style.display = 'block';
 
</script>
 
now by default none javascript is followed and if the script is executed (meaning javascript is on) it gets hidden and the javascript content gets shown.
 
if you where using mainly just html this would be the new way to go as it does not effect the html doc size by much (factor when dealing with Search engine optimisation)
 
but if you are using a server side language its best to build these tags on the server side with the server side knowing that javascript is enabled. you can use my methods and if you are willing to lay down some cash , you can always get browserhawk , even though its a .net component it can also work on cold fusion (7 & 8) and asp.
 
Hope this helps.
 
Chona1171
Web Developer (C#), Silverlight

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 13 Aug 2012
Article Copyright 2009 by Chona1171
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid