谁能帮助我尝试检查是否使用Java代码在客户端浏览器中启用了JavaScript。
假设您正在编写Java Web应用程序,我成功使用的一种技术是让访问的第一页(通常是登录表单)在页面加载时编写会话cookie。然后,获取表单提交的Java代码以检查该cookie的存在。
在客户端上:
<script type="text/javascript"> function createCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } var cookie = name + "=" + value + expires + "; path=" + "/"; document.cookie = cookie; } createCookie("JavaScriptEnabledCheck", 1, 0); </script>
在服务器上:
/** * Returns <code>true</code> if the session cookie set by the login form * is not present. * * @param request The HTTP request being processed * @return <code>true</code> if JavaScript is disabled, otherwise <code>false</code> */ private boolean isJavaScriptDisabled(HttpServletRequest request) { boolean isJavaScriptDisabled = true; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if ("JavaScriptEnabledCheck".equalsIgnoreCase(cookies[i].getName())) { isJavaScriptDisabled = false; break; } } } return isJavaScriptDisabled; }