0

I am trying to detect whether the client has their CapsLock enabled by temporarily creating a hidden input field, triggering a keyup event on that input, and then checking the boolean value of e.getModifierState('CapsLock').

The function I've written is below, which currently throws the error Uncaught TypeError: e.getModifierState is not a function on the line which includes e.getModifierState and I'm struggling to diagnose why this is occurring. I'm open to any help here!

let checkCaps = () => {
    let tempInput = document.createElement('input');
    let keyupEvent = new Event('keyup');
    tempInput.type = 'hidden';
    tempInput.id = 'check-caps';
    let capsOn = false;
    tempInput.addEventListener('keyup', e => {
        e.which = 65;
        capsOn = e.getModifierState('CapsLock');
    })
    tempInput.dispatchEvent(keyupEvent);
    tempInput.remove();
    return capsOn;
}

checkCaps(); // testing the function
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
  • 1
    You haven't specified the type for the dispatched event, create a `KeyboardEvent` instead of `Event`. – Teemu Apr 09 '21 at 15:41

1 Answers1

1

The class Event is the base class for all specific event classes. If you want to generate a keyboard event, then you must use the KeyboardEvent class like this:

    let checkCaps = () => {
    let tempInput = document.createElement('input');
    let keyupEvent = new KeyboardEvent('keyup');
    tempInput.type = 'hidden';
    tempInput.id = 'check-caps';
    let capsOn = false;
    tempInput.addEventListener('keyup', e => {
        e.which = 65;
        capsOn = e.getModifierState('CapsLock');
    })
    tempInput.dispatchEvent(keyupEvent);
    tempInput.remove();
    return capsOn;
}

checkCaps(); // testing the function

If tested this and the code runs, but I always get false for getModifierState('CapsLock')

It seems that for you must specify the current value self-generated KeyboardEvents. But this isn't what you want. It seems that other people had the same issue and there is no solution without real user input.

See: How to detect Caps Lock state on page load (that is, not on keypress) with JavaScript?

David Gausmann
  • 1,570
  • 16
  • 20