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

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

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


当前回答

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

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

其他回答

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

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

您会想看一下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>

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请求不会减慢页面的呈现速度。

当浏览器中没有启用js时,<noscript>标记中的代码将被执行。 我们可以使用noscript标签来显示msg来打开JS,如下所示。

<noscript>
    <h1 style="text-align: center;">
       To view this page properly, please 
       enable JavaScript and reload the page
    </h1>
</noscript>

同时保持我们的网站内容在身体隐藏。如下

<body>
<div id="main_body" style="display: none;">
    website content.
</div>
</body>

现在如果JS是打开的,你可以让main_body中的内容可见,如下所示

<script type="text/javascript">
    document.getElementById("main_body").style.display="block";
</script>

我要在这里加上。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所做的…如果它对谷歌来说足够好,它对我的小网站来说就足够好了。