Detecting Javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
programmermatt
Forum Commoner
Posts: 65
Joined: Tue Mar 15, 2005 5:03 pm
Contact:

Detecting Javascript

Post by programmermatt »

I was wondering what would be the best way to auto-detect javascript ability. I was thinking of something like this:

Code: Select all

<html>
 <head>
  <meta http-equiv=&quote;refresh&quote; content=&quote;2;url=index.php?js=0&quote;>
 </head>
<body>
<script type=&quote;text/javascript&quote;>
   document.location.href = &quote;index.php?js=1&quote;;
</script>
</body>
</html>
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

why not just use

Code: Select all

<noscript>
programmermatt
Forum Commoner
Posts: 65
Joined: Tue Mar 15, 2005 5:03 pm
Contact:

Post by programmermatt »

Because I want to know on the PHP side wether they have javascript so I can conditionally output javascript to them or not and they don't have to worry about selecting wether or not they have javascript in their profiles and also allows guests to use the javascript features without logging in.
programmermatt
Forum Commoner
Posts: 65
Joined: Tue Mar 15, 2005 5:03 pm
Contact:

Post by programmermatt »

I came up with this and was wondering if anyone sees potential problems with my javascript detection:

Code: Select all

// this _short_ section of code handles javascript detection
// js= 0 (no js) 1 (js) 2 (js+ajax)
if( !isset($_SESSION['javascript']) ) {
	if( !isset($_GET['js']) ) {
		ob_clean(); echo "<html><head><meta http-equiv=\"refresh\" content=\"1;url=index.php?js=0\">
		</head><body>Detecting Javascript..<script type=\"text/javascript\">
		try{ request = new XMLHttpRequest(); }catch(e){
			try{ request = new ActiveXObject(\"Microsoft.XMLHTTP\");
			}catch(e) { document.location.href = \"index.php?js=1\"; }
		}; document.location.href = \"index.php?js=2\";</script></body></html>";
		ob_flush();exit;
	} else $_SESSION['javascript'] = $_GET['js'];
}
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post by Roja »

programmermatt wrote:Because I want to know on the PHP side wether they have javascript so I can conditionally output javascript to them or not and they don't have to worry about selecting wether or not they have javascript in their profiles and also allows guests to use the javascript features without logging in.
You don't need to.

If they don't support javascript, their browser will not download the javascript (unless it is inline, and it shouldnt be - it should be a standalone file, so it can be cached!). This is true on IE, Firefox, Konqueror, AND Opera.

Instead, as suggested, you simply put the fallback functionality in a <noscript> tag.

As to detecting it, I always suggest http://phpsniff.sourceforge.net
Post Reply