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

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

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


当前回答

在什么地方发现它?JavaScript ?那是不可能的。如果只是为了记录日志,可以使用某种跟踪方案,其中每个页面都有JavaScript,将对一个特殊资源(可能是一个非常小的gif或类似的文件)发出请求。这样,您就可以获取唯一页面请求和跟踪文件请求之间的差异。

其他回答

您会想看一下noscript标记。

<script type="text/javascript">
...some javascript script to insert data...
</script>
<noscript>
   <p>Access the <a href="http://someplace.com/data">data.</a></p>
</noscript>

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

例如,您可以使用document之类的东西。Location = 'java_page.html'将浏览器重定向到一个新的脚本加载页面。重定向失败意味着JavaScript不可用,在这种情况下,您可以求助于CGI程序或在标记之间插入适当的代码。(注意:NOSCRIPT仅在Netscape Navigator 3.0及更高版本中可用。)

信贷 http://www.intranetjournal.com/faqs/jsfaq/how12.html

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...

人们已经发布了一些例子,这些例子都是很好的检测选项,但是基于你的要求“给出警告,如果浏览器没有启用JS,站点将无法正常运行”。你可以添加一个元素,让它以某种方式出现在页面上,例如当你获得徽章时,在Stack Overflow上弹出相应的消息,然后用一些Javascript删除它,在页面加载时立即运行(我指的是DOM,而不是整个页面)。