今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。
有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。
最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。
今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。
有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。
最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。
当前回答
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请求不会减慢页面的呈现速度。
其他回答
我要在这里加上。02。虽然不是百分百防弹,但我觉得已经足够了。
对我来说,问题是,在我喜欢的例子中,提出一些“没有Javascript,这个网站不能很好地工作”的信息,然后你需要确保你的网站在没有Javascript的情况下也能正常工作。一旦你开始走上这条路,你就会开始意识到,关闭JS后,网站应该是防弹的,这是一大块额外的工作。
所以,你真正想要的是“重定向”到一个页面,上面写着“打开JS,傻瓜”。但是,当然,你不能可靠地做元重定向。所以,我的建议是:
<noscript>
<style type="text/css">
.pagecontainer {display:none;}
</style>
<div class="noscriptmsg">
You don't have javascript enabled. Good luck with that.
</div>
</noscript>
...你站点中的所有内容都是用一个div类“pagcontainer”来包装的。noscript标签内的CSS将隐藏所有页面内容,而不是显示你想要显示的任何“无JS”消息。这实际上是Gmail所做的…如果它对谷歌来说足够好,它对我的小网站来说就足够好了。
您会想看一下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,我将每个链接的“href”属性设置为相同的文档,这将通知用户启用javascript或下载Firefox(如果他们不知道如何启用javascript)。我将实际链接url存储到链接的“name”属性,并定义了一个全局onclick事件,读取“name”属性并将页面重定向到那里。
这对我的用户基础很有效,虽然有点法西斯;)。
这是我使用的“最干净”的解决方案:
<noscript>
<style>
body *{ /*hides all elements inside the body*/
display: none;
}
h1{ /* even if this h1 is inside head tags it will be first hidden, so we have to display it again after all body elements are hidden*/
display: block;
}
</style>
<h1>JavaScript is not enabled, please check your browser settings.</h1>
</noscript>
在主体上使用.no-js类,并基于.no-js父类创建非javascript样式。 如果javascript被禁用,你会得到所有的非javascript样式, 如果有JS支持,.no- JS类将被替换,像往常一样提供所有的样式。
document.body.className = document.body.className.replace("no-js","js");
通过modernizr在HTML5样板http://html5boilerplate.com/中使用的技巧,但你可以使用一行javascript来替换类
Noscript标签是可以的,但是为什么在你的HTML中有额外的东西,当它可以用CSS完成时