![]() |
Web Development »
ASP.NET »
Howto
Beginner
License: The Code Project Open License (CPOL)
Detect if JavaScript is enabled in ASPXBy ShawnDevinCheck if the browser has JavaScript enabled in the Page_Load method. |
Javascript, C# 1.0, C# 2.0, C# 3.0.NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0, .NET 3.5, ASP.NET, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
This code sample detects if the current browser currently has JavaScript enabled.
I searched for a way to determine if the user's web browser was running JavaScript, but discovered most samples on the net only detected if the browser was capable of running JavaScript and which version of JavaScript the browser is able to run. It did nothing to detect (at least from C#) whether JavaScript was currently enabled.
I finally found four tutorials which I have combined bits of into one simple block of code that can be run from the Page_Load() method to see if JavaScript is enabled on a client's web browser or not.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["JSChecked"] == null)
//JSChecked -indicates if it tried to run the javascript version
{
// prevent infinite loop
Session["JSChecked"] = "Checked";
string path = Request.Url + "?JScript=1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect",
"window.location.href='" + path + "';", true);
}
if (Request.QueryString["JScript"] == null)
Response.Write("JavaScript is not enabled.");
else
Response.Write("JavaScript is enabled.");
}
The greatest difficulty was that most tutorials for this type of function on the web all recommend using the following code:
Response.Write(@"<script language="'javascript'" type='text/jscript'>" +
@" window.location = 'default.aspx?JScript=1'; </script>");
Unfortunately, this code does not work if the browser is Firefox. However, using the command:
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect",
"window.location.href='default.aspx?JScript=1';", true);
works for all browsers that I have tested (IE, Firefox, Safari, and Opera).
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 22 Feb 2008 Editor: Smitha Vijayan |
Copyright 2008 by ShawnDevin Everything else Copyright © CodeProject, 1999-2009 Web21 | Advertise on the Code Project |