今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。
有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。
最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。
今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。
有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。
最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。
当前回答
为了强制用户启用javascript,我将每个链接的“href”属性设置为相同的文档,这将通知用户启用javascript或下载Firefox(如果他们不知道如何启用javascript)。我将实际链接url存储到链接的“name”属性,并定义了一个全局onclick事件,读取“name”属性并将页面重定向到那里。
这对我的用户基础很有效,虽然有点法西斯;)。
其他回答
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...
在meta noscript内部添加刷新不是一个好主意。
因为noscript标签不符合XHTML 属性值“Refresh”是非标准的,不应该使用。“刷新”将页面的控制权从用户手中夺走。使用“刷新”将导致W3C的Web内容可访问性指南失败 ——参考http://www.w3schools.com/TAGS/att_meta_http_equiv.asp。
使用我在这里介绍的纯服务器端解决方案检查cookie,然后使用Jquery删除cookie来检查javascript。Cookie,然后检查Cookie,这种方式你检查Cookie和javascript
我建议您反过来编写不引人注目的JavaScript。
使您的项目的功能为禁用JavaScript的用户工作,当您完成后,实现您的JavaScript ui增强。
https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
更新2022
这个问题已经有30多个答案,但似乎没有一个答案清楚或准确地说明必须做什么。
服务器端框架使用- ASP。网络核心 客户端-香草js
在BaseController上,也就是应用的第一个入口点OnActionExecutionAsync上,我有这个逻辑。
基本上默认情况下,我假设客户端没有启用javascript并设置此标志。
Response.Cookies.Append("jsEnabled", "false");
现在,在客户端初始加载后,我有一个javascript函数,将这个标志更新为true。 这个函数只有在环境中有javascript时才会运行
完整的解在这里。
客户端
在初始负载上添加此函数
function detectIfJavascriptIsEnabled() {
// if this function run's which means js is enabled
var jsEnabled = getCookie('jsEnabled');
if (jsEnabled === 'false') {
setCookie('jsEnabled', 'true');
location.reload();
}
}
服务器
private bool ValidateIfEnvironmentHasJavascript() {
if (HttpContext.Request.Cookies != null && HttpContext.Request.Cookies.Count > 0) {
Boolean.TryParse(HttpContext.Request.Cookies["jsEnabled"], out
var hasJavascriptEnabled);
return hasJavascriptEnabled;
} else {
Response.Cookies.Append("jsEnabled", "false",
new CookieOptions() {
IsEssential = true, Expires = DateTime.UtcNow.AddHours(24)
});
}
return false;
}
这就是得到结果的方法
var environmentHasJavascript = ValidateIfEnvironmentHasJavascript();