今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。

有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。

最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。


当前回答

更新2022

这个问题已经有30多个答案,但似乎没有一个答案清楚或准确地说明必须做什么。

服务器端框架使用- ASP。网络核心 客户端-香草js

在BaseController上,也就是应用的第一个入口点OnActionExecutionAsync上,我有这个逻辑。

基本上默认情况下,我假设客户端没有启用javascript并设置此标志。

Response.Cookies.Append("jsEnabled", "false");

现在,在客户端初始加载后,我有一个javascript函数,将这个标志更新为true。 这个函数只有在环境中有javascript时才会运行

完整的解在这里。

客户端

在初始负载上添加此函数

function detectIfJavascriptIsEnabled() {
    // if this function run's which means js is enabled
    var jsEnabled = getCookie('jsEnabled');
    if (jsEnabled === 'false') {
        setCookie('jsEnabled', 'true');
        location.reload();
    }
}

服务器

private bool ValidateIfEnvironmentHasJavascript() {
  if (HttpContext.Request.Cookies != null && HttpContext.Request.Cookies.Count > 0) {
    Boolean.TryParse(HttpContext.Request.Cookies["jsEnabled"], out
      var hasJavascriptEnabled);
    return hasJavascriptEnabled;
  } else {
    Response.Cookies.Append("jsEnabled", "false",
      new CookieOptions() {
        IsEssential = true, Expires = DateTime.UtcNow.AddHours(24)
      });
  }

  return false;
}

这就是得到结果的方法

var environmentHasJavascript = ValidateIfEnvironmentHasJavascript();

其他回答

noscript标记工作得很好,但是需要每个额外的页面请求来继续提供无用的JS文件,因为noscript本质上是一个客户端检查。

你可以用JS设置一个cookie,但正如其他人指出的那样,这可能会失败。理想情况下,您希望能够检测到JS客户端,并且不使用cookie,为该用户设置会话服务器端,以指示是否启用JS。

A possibility is to dynamically add a 1x1 image using JavaScript where the src attribute is actually a server side script. All this script does is saves to the current user session that JS is enabled ($_SESSION['js_enabled']). You can then output a 1x1 blank image back to the browser. The script won't run for users who have JS disabled, and hence the $_SESSION['js_enabled'] won't be set. Then for further pages served to this user, you can decide whether to include all of your external JS files, but you'll always want to include the check, since some of your users might be using the NoScript Firefox add-on or have JS disabled temporarily for some other reason.

您可能希望将此检查包含在接近页面末尾的位置,以便额外的HTTP请求不会减慢页面的呈现速度。

Why don't you just put a hijacked onClick() event handler that will fire only when JS is enabled, and use this to append a parameter (js=true) to the clicked/selected URL (you could also detect a drop down list and change the value- of add a hidden form field). So now when the server sees this parameter (js=true) it knows that JS is enabled and then do your fancy logic server-side. The down side to this is that the first time a users comes to your site, bookmark, URL, search engine generated URL- you will need to detect that this is a new user so don't look for the NVP appended into the URL, and the server would have to wait for the next click to determine the user is JS enabled/disabled. Also, another downside is that the URL will end up on the browser URL and if this user then bookmarks this URL it will have the js=true NVP, even if the user does not have JS enabled, though on the next click the server would be wise to knowing whether the user still had JS enabled or not. Sigh.. this is fun...

将此添加到每页的HEAD标记。

<noscript>
        <meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>

所以你有:

<head>
    <noscript>
        <meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
    </noscript>
</head>

感谢杰。

我过去使用的一种技术是使用JavaScript编写一个会话cookie,它只是作为一个标志,表示启用了JavaScript。然后服务器端代码查找此cookie,如果没有找到,则采取适当的操作。当然,这种技术确实依赖于启用cookie !

<noscript>甚至不是必需的,更不用说在XHTML中不受支持了。

工作的例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
    <title>My website</title>
    <style>
      #site {
          display: none;
      }
    </style>
    <script src="http://code.jquery.com/jquery-latest.min.js "></script>
    <script>
      $(document).ready(function() {
          $("#noJS").hide();
          $("#site").show();
      });
    </script>
</head>
<body>
    <div id="noJS">Please enable JavaScript...</div>
    <div id="site">JavaScript dependent content here...</div>
</body>
</html>

在本例中,如果启用了JavaScript,则可以看到站点。如果没有,则会看到“请启用JavaScript”消息。测试JavaScript是否启用的最好方法是简单地尝试和使用JavaScript!如果它工作,它被启用,如果没有,那么它不是…