How can I tell if a user has JavaScript enabled?

Because ColdFusion is a server side technology and JavaScript is a client side technology, you will need to use a 2 page check to see if JavaScript is enabled. Your first page will perform the "is JavaScript enabled" test; your second page will display or record the results (save in a session variable etc).

One way to accomplish this task would be to set a cookie in JavaScript, and then test for the existence of this cookie via ColdFusion. If the cookie exists, then you know JavaScript is enabled.

<!--- Page1.cfm --->
<script language="JavaScript">
<!--
function setCookie(name, value) {
 var expDate = new Date()
 expDate.setTime(expDate.getTime() + 60*60*1000);
 document.cookie = name + "=" + escape(value) + ";" + expDate.toGMTString();
}
setCookie('JSCookie', 'true!');
// -->
</script>
<!--- Page2.cfm --->
<cfoutput>#cookie.JSCookie#</cfoutput>

Another way to test for JavaScript is to use a JavaScript redirect. If the browser supports JavaScript, it will be redirected. You could also use a HTML Meta redirect to catch all instances that ignored the JavaScript redirection, and redirect them to a set of non-JavaScript enabled pages. The code would look as follows:

<script language="JavaScript">
<!-- Begin script
     window.location.replace("hasJS.cfm");
// End script -->
</script>
<html>
<head>
        <META HTTP-EQUIV=REFRESH CONTENT="0;URL=noJS.cfm">
</head>
</html>

This question was written by Jeremy Petersen
It was last updated on June 13, 2006.

Categories

JavaScript

Comments

comments powered by Disqus