使用Rails检查Javascript是否已启用(Serverside) [英] Check if Javascript is Enabled (Serverside) with Rails

查看:134
本文介绍了使用Rails检查Javascript是否已启用(Serverside)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查Rails中是否启用了javascript?所以我可以在视图中做这样的事情:

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>


推荐答案

你可以检测到它,但它不漂亮。

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

接下来,您需要在所有页面中包含javascript操作,以便在每次页面加载时调用此控制器操作。最简单的方法是将它包含在你的布局中包含的javascript-confirm.js文件中(在这个特定的例子中我使用了Prototype的Ajax.Request,所以你需要将它包含在你的javascripts中):

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

你现在将在所有控制器中都有一个名为 @javascript_active 的变量。

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

即使用户激活/停用javascript,它也应该有效,精度为10秒。如果您的某些页面加载时间超过10页(即包含大量图像),则可能无效。在这种情况下增加时间限制(在applicationcontroller和你的javascript上)

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)

免责声明:我没有测试过这段代码,一些bug可能潜伏着 - 但它应该指向你在正确的方向上。

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

这篇关于使用Rails检查Javascript是否已启用(Serverside)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆