can anyone help me in trying to check whether JavaScript is enabled in client browser using Java code.
JavaScript is widely used in all newer versions of web browsers (Chrome, Firefox, Internet Explorer, Safari, Opera), where it is enabled by default.
If JavaScript is enabled then it updates the default "No" answer in to a "Yes" answer! (so that if JavaScript is not enabled, the default "No" remains as the answer).
Assuming you're writing a Java web application, one technique that I've used successfully is to have the first page that's accessed—typically a login form—write a session cookie when the page loads. Then have the Java code that the form submits to check for the existence of that cookie.
On the client:
<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>
On the server:
/**
* 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;
}
In yourform for you can put code like this:
<noscript>
<input type="hidden" name="JavaScript" value="false" />
</noscript>
The parameter should only be submitted if the browser has scripts turned off. In your Java applications you can check it like so:
boolean javaScript = request.getParameter("JavaScript") == null;
If a form submit is performed, you can put a hidden input in the form and fill out its value with javascript (from OnSubmit) and check that on the server side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With