By Lance Pollard


2010-02-23 01:54:10 8 Comments

How would you check if javascript is enabled in Rails? So that I could do something like this in the views:

<div>
    <% if javascript_enabled? %>
    <p>Javascript Enabled!</p>
    <%- else -%>
    <p>No Javascript</p>
    <%- end -%>
</div>

7 comments

@User16119012 2013-06-20 10:39:49

Instead of writing lots of code to check whether your javascript is enable or not, you can simply write as(using HAML) in your page layout-

%p.javascript_require
  No javascript, please enable JavaScript

and make your javascript hide this paragraph using hide() function as -

$(".javascript_require").hide();

Do whatever function you want to perform when if javascript is disabled.

@Patrick 2011-12-08 01:10:43

If that's all you want it to do, it might be best to put the non-JS version in the view:

<p class="replace_by_js">No Javascript</p>

and then have the Javascript replace that: (I use jQuery)

$('p.replace_by_js').replaceWith("<p>Javascript Enabled!</p>")

This approach should be usable for practically any progressive enhancement you want to add.

@Ervin Nemesszeghy 2010-10-18 15:46:21

You cannot check from the server side if Javascript is enabled, however, you can set up a page before you site, and let redirect to your application with a parameter indicating if Javascript is enabled. See the sample code below :

<html>
<head>
    <meta HTTP-EQUIV="REFRESH" content="2; url=./Login.action?javascriptEnabled=false">
    <link rel="icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
    <title></title>
</head>
<body onload="window.location.href='./Login.action?javascriptEnabled=true'" ></body>
</html>

So, if Javascript enabled the onload redirect will work, if not then the header meta tag will work. The trick is to put 1-2 second delay on the meta tag redirect, so if the javascript redirect won't redirect, the meta tag will, indicating that no JavaScript is enabled.

@kikito 2010-02-23 08:48:15

You can detect it, but it isn't pretty.

First, you need a new controller with an action that updates a timeout in the session:

class JavascriptController < ApplicationController
  def confirm
    session[:javascript_updated] = Time.now
  end
end

Next you need to include a javascript action in all your pages so this controller action is called on each page load. The easiest way is to include it on a "javascript-confirm.js" file included in your layout (on this particular example I used Prototype's Ajax.Request, so you need to have it included on your javascripts, too):

function confirmJavascript()
{
    // Assuming you are using Prototype
    new Ajax.Request('/JavascriptController/confirm');
}

myTimeoutFunction();
setInterval(myTimeoutFunction, 10000); // invoke each 10 seconds

This will invoke the confirm action in all your page views. Finally, you have to control how much time did it pass since your last confirmation in your application controller.

class ApplicationController < ActionController::Base

JAVASCRIPT_TIME_LIMIT = 10.seconds

before_filter :prepare_javascript_test

private
def prepare_javascript_test
  if (session[:javascript_updated].blank? or
     Time.now - session[:javascript_updated] > ApplicationController::JAVASCRIPT_TIME_LIMIT)
    @javascript_active = true
  else
    @javascript_active = false
  end
end

end

You will now have a variable called @javascript_active in all your controllers.

It should work even when the user activates/deactivates javascript, with a precision of 10 seconds. It might not work if some of your pages take longer than 10 pages to load (i.e. with lots of images). Increase the time limit in that case (on applicationcontroller and your javascript)

Disclaimer: I haven't tested this code, some bugs might be lurking - but it should point you on the right direction.

@bobince 2010-02-23 02:21:15

You can't detect it on the server-side. Indeed, scripting might be turned off the first time your page is accessed, then the browser settings changed and re-navigated without a new HTTP request being made. Not to mention all sorts of caching issues and places where scripting might be technically ‘enabled’ but not working due to conflicts, bugs or ‘security’ tools getting in the way.

So you need to do all decisions about content for with-script/without-script on the client side. These days the preferred method would generally be ‘progressive enhancement’: include the basic HTML version on the page, then have JavaScript replace/upgrade it where it can:

<div id="isitjs">
    <p>Backup content for no JavaScript</p>
</div>
<script type="text/javascript">
    document.getElementById('isitjs').innerHTML= '<p>Sparkly script-enhanced content!<\/p>';
    // or DOM methods, as you prefer
</script>

@Peter Brown 2010-02-23 02:08:53

You could do something sort of hacky like this, but your "javascript-enabled" html would need to be generated within the helper

Put this in your application_helper.rb

def javascript_enabled?
  content_tag(:div, [
    content_tag(:script, 'document.write("Javascript Enabled")'), 
    content_tag(:noscript, 'No Javascript')
  ])
end

This goes in your view:

<%= javascript_enabled? %>

@BalusC 2010-02-23 01:58:32

That's not possible during rendering of the response. The only way to figure that less or more reliable is to let the client send an ajaxical request beforehand in one of the previous requests. This ajaxical request should then set some token in the server side session which identifies that the client has sent an ajaxical request beforehand (which thus proves that the client has JS enabled). But that doesn't cover the possibility that the client can disable JS in meanwhile during a session. Or you must hassle with collecting timestamps and ajaxical requests after every response. Not really something you'd like to do.

Rather render the both contents and make use of <noscript> and <script> tags to toggle the one or other. Also see my answer here for several examples: opposite of <noscript>.

Related Questions

Sponsored Content

89 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6157650 View
  • 7682 Score
  • 89 Answer
  • Tags:   javascript arrays

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

65 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

23 Answered Questions

[SOLVED] Check if a variable is a string in JavaScript

  • 2010-10-30 14:36:34
  • Olical
  • 1254535 View
  • 1562 Score
  • 23 Answer
  • Tags:   javascript

86 Answered Questions

[SOLVED] How do JavaScript closures work?

47 Answered Questions

3 Answered Questions

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

Sponsored Content