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

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

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


当前回答

这是为我工作:它重定向访问者如果javascript被禁用

<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>

其他回答

如果javascript被禁用,您的客户端代码将无法运行,所以我假设您的意思是您希望该信息可用的服务器端。在这种情况下,noscript就没那么有用了。相反,我有一个隐藏的输入,并使用javascript填充一个值。在你的下一个请求或回发后,如果值在那里,你知道javascript是打开的。

注意像noscript这样的事情,第一次请求可能显示javascript被禁用,但以后的请求会打开它。

我认为你可以在noscript标签中插入一个图像标签,并查看你的站点有多少次以及这个图像被加载的频率。

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

我假设您正在决定是否交付javascript增强的内容。最好的实现能够干净地降级,因此站点在没有JavaScript的情况下仍然可以运行。我还假定您指的是服务器端检测,而不是出于某种无法解释的原因使用<noscript>元素。

没有执行服务器端JavaScript检测的好方法。作为一种替代方法,可以使用JavaScript设置一个cookie,然后在后续的页面视图中使用服务器端脚本测试该cookie。然而,这并不适合决定要传递什么内容,因为它无法区分没有cookie的访问者与新访问者或不接受JavaScript集cookie的访问者。

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