How to detect Caps Lock is ON on web browser on Android Devices using JavaScript?

1.1k Views Asked by At

We can very well detect CapsLock is ON/not on iPhone web browser using KeyboardEvent.getModifierState(), with sample code,

function checkCapsLock(e) {
  if (e.getModifierState("CapsLock")) {
    alert("Caps ON");
  }
}

But it doesn't work on a browser on Android Devices. I've tried many other solutions using charCode, keyCode, shiftKey, which, etc. methods on the event with listeners like keyup, keydown, keypress, etc. But no luck.

I've gone through the answers mentioned on stackoverflow, and other links too. But still no luck.

Is there any workaround for this?

I'm asking about the issue on the Android web browser!

With Key Event Viewer, we can observe that CapsLock can be detected on Web or mobile web browser on iPhone, but not on a web browser on Android devices.

1

There are 1 best solutions below

1
Hackinet On

While this code works on some Android devices, it won't work on all, because the e.ShiftKey turns out to be false in Android. On android, it actually depends on your keyboard.

This is the best, I was able to come up with.

document.addEventListener ('keyup', function (event){ 
        
    let status = checkCapsLock(event);
    
    document.getElementById("status").innerHTML += ('<span class="'+ status +'">Status: ' + status + '</span>');

});  
 

function checkCapsLock(e) {
  e = e ? e : window.event;
  
  if (e.getModifierState('CapsLock'))
    return true;
    
  let isShiftOn = e.shiftKey;
  
  let s = e.key;
  
  if(s.length != 1){
  let keyCode = e.keyCode; //e.KeyCode is always 229 on Android;
      if(keyCode == 229) 
        s = (e.target.value).split('').pop();
  }
     
  if ( (s.length != 0 ) && (s.toUpperCase() === s) && !isShiftOn )
        return true;
  return false;
}
span{
  display: block;
  background: red;
}

span.true{
  background: green;
}
Input: <input id="targetInput">
<p id="status"></p>