今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。
有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。
最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。
今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。
有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。
最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。
当前回答
也许听起来很奇怪,但你可以试一试:
<?php $jsEnabledVar = 0; ?>
<script type="text/javascript">
var jsenabled = 1;
if(jsenabled == 1)
{
<?php $jsEnabledVar = 1; ?>
}
</script>
<noscript>
var jsenabled = 0;
if(jsenabled == 0)
{
<?php $jsEnabledVar = 0; ?>
}
</noscript>
现在在整个页面中使用'$jsEnabledVar'的值。你也可以用它来显示一个块,告诉用户JS被关闭了。
希望这能有所帮助
其他回答
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,而不是整个页面)。
因为我总是想给浏览器一些有价值的东西,我经常使用这个技巧:
首先,页面中任何需要JavaScript才能正常运行的部分(包括通过getElementById调用等修改的被动HTML元素)都被设计成可用的,假设没有可用的JavaScript。(设计得好像它不存在一样)
任何需要JavaScript的元素,我在标签中放置如下内容:
<span name="jsOnly" style="display: none;"></span>
然后在文档的开头,使用.onload或document。在getElementsByName('jsOnly')的循环中设置.style。Display = "";重新打开JS依赖的元素。这样,非JS的浏览器就不需要看到站点中依赖于JS的部分,如果他们拥有它,它会在准备就绪时立即显示出来。
一旦您习惯了这种方法,就很容易混合您的代码来处理这两种情况,尽管我现在只是在试验noscript标记,并期望它会有一些额外的优点。
我建议您反过来编写不引人注目的JavaScript。
使您的项目的功能为禁用JavaScript的用户工作,当您完成后,实现您的JavaScript ui增强。
https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
如果你的用例是你有一个表单(例如,一个登录表单),你的服务器端脚本需要知道用户是否启用了JavaScript,你可以这样做:
<form onsubmit="this.js_enabled.value=1;return true;">
<input type="hidden" name="js_enabled" value="0">
<input type="submit" value="go">
</form>
这将在提交表单之前将js_enabled的值更改为1。如果服务器端脚本得到0,则没有JS。如果它得到1,JS!