detect keyboard layout with javascript

后端 未结 5 741
盖世英雄少女心
盖世英雄少女心 2020-11-29 08:47

Is there any way to detect the current keyboard layout using JavaScript? I found this, but it only detects if the visitor is on the english layout. I need to know the exact

5条回答
  •  孤街浪徒
    2020-11-29 09:15

    All what I know about this topic and already implemented a solution for it, is to detect non English layout keyboard, i.e Languages that uses any alphabet other than that used in English. The solution is depend on regular expression to match any word character \w, any digit character \d and a range of predefined English keyboard special characters, so any other characters, such as Arabic, Japanese, etc, will not match, all this uses keydown event and I am using this solution to restrict and notify usernames and passwords fields entry in login form. I packaged it in a function like the following:

    function checkKeyboard(ob,e){
            re = /\d|\w|[\.\$@\*\\\/\+\-\^\!\(\)\[\]\~\%\&\=\?\>\<\{\}\"\'\,\:\;\_]/g;
          a = e.key.match(re);
          if (a == null){
            alert('Error 2:\nNon English keyboard layout is detected!\nSet the keyboard layout to English and try to fill out the field again.');
            ob.val('');
            return false;
          }
          return true;
        } 
    

    Then call the function from the event as the following:

    $("#textFieldId").keydown(function(e){
            if (!checkKeyboard($(this),e)){
                return false;
            }
        });
    

    This is Working DEMO for unknown down voters!

    Notice:

    In the regex pattern, re you are able to add any missing special characters such as #,`,|, etc

提交回复
热议问题