Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether JavaScript is enabled in client browser using Java code

can anyone help me in trying to check whether JavaScript is enabled in client browser using Java code.

like image 450
Sai Prasad Avatar asked Apr 20 '09 13:04

Sai Prasad


People also ask

Is JavaScript automatically enabled?

JavaScript is widely used in all newer versions of web browsers (Chrome, Firefox, Internet Explorer, Safari, Opera), where it is enabled by default.

What happens if JavaScript is enabled?

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).


3 Answers

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;
}
like image 193
John Topley Avatar answered Oct 13 '22 12:10

John Topley


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;
like image 32
pjesi Avatar answered Oct 13 '22 12:10

pjesi


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.

like image 28
mitchnull Avatar answered Oct 13 '22 11:10

mitchnull