Javascript key event of is compatible with all browsers

  • 2020-03-30 01:00:24
  • OfStack

Part 1: browser button events

To implement keylogger with js, we should pay attention to three key event types in the browser, namely keydown, keypress and keyup, which correspond to the three event handles of onkeydown, onkeypress and onkeyup respectively. A typical key produces all three of these events: keydown, keypress, and then keyup when the key is released.

Of the three event types, keydown and keyup are lower level, while keypress is higher level. By advanced, I mean that when the user presses shift + 1, keypress parses the key event and returns a printable "!" Keydown and keyup just record the shift + 1 event. [1]

However, keypress is only valid for some characters that can be printed out. For function keys such as f1-f12, Backspace, Enter, Escape, PageUP, PageDown, and arrow direction, keypress events are not generated, but keydown and keyup events can be generated. In FireFox, however, feature buttons can generate keypress events.

The event objects passed to the keydown, keypress, and keyup event handles have some common properties. If Alt, Ctrl, or Shift are pressed with a key, this is represented by the altKey, ctrlKey, and shiftKey properties of the event, which are common in FireFox and IE.

Part 2: browser compatibility

All involve browser js, must consider the browser compatibility question.
Currently, there are two major categories of commonly used browsers, IE and Mozilla. Maxthon is based on the IE kernel, while FireFox and Opera are based on the Mozilla kernel.

2.1 initialization of events

The first thing you need to know is how to initialize the event. The basic statement is as follows:

The function keyDown () {}
Document. The onkeydown = keyDown;

When the browser reads this statement, the KeyDown() function is called whenever any key on the keyboard is pressed.

2.2 implementation methods of FireFox and Opera

Programs like FireFox and Opera are more cumbersome to implement than IE, so let's describe them here.

The keyDown() function has a hidden variable -- typically, we use the letter "e" for this variable.

The function keyDown (e)

The variable e represents the keystroke event. To find out which key was pressed, use the property which:

E.w hich

E.which will give the index value of the key, and the method to convert the index value to the letter or number value of the key requires the static function string.fromcharcode (), as follows:

String. FromCharCode (e.w hich)

By putting the above statements together, we can see which key is being pressed in FireFox:


   function keyDown(e) { 
      var keycode = e.which; 
      var realkey = String.fromCharCode(e.which); 
      alert(" The key code : " + keycode + "  character : " + realkey); 
   } 
   document.onkeydown = keyDown; 

2.3 implementation method of IE

IE program does not need e variable, use window.event.keycode to replace e.wahich, the key index value into the real key value method is similar to: string.fromcharcode (event.keycode), the program is as follows:


   function keyDown() { 
      var keycode = event.keyCode; 
      var realkey = String.fromCharCode(event.keyCode); 
      alert(" The key code : " + keycode + "  character : " + realkey); 
   } 
   document.onkeydown = keyDown; 

2.4 determine the browser type

The above is to understand how to achieve the method of obtaining the key event object in various browsers, then the following needs to determine the browser type, this method is many, there are more convenient to understand, there are also very clever ways, let me first say the general method: AppName property of navigator object is used, of course, also can use the userAgent property, here with appName to determine the browser type, IE and Maxthon's appName is "Microsoft Internet Explorer", and FireFox and Opera's appName is "Netscape", so a relatively simple function of the code as follows:


   function keyUp(e) { 
      if(navigator.appName == "Microsoft Internet Explorer") 
      { 
        var keycode = event.keyCode; 
        var realkey = String.fromCharCode(event.keyCode); 
      }else 
      { 
         var keycode = e.which; 
          var realkey = String.fromCharCode(e.which); 
      } 
      alert(" The key code : " + keycode + "  character : " + realkey); 
    } 
   document.onkeyup = keyUp; 

The simpler way is [2] :

   function keyUp(e) { 
     var currKey=0,e=e||event; 
     currKey=e.keyCode||e.which||e.charCode; 
     var keyName = String.fromCharCode(currKey); 
     alert(" The key code : " + currKey + "  character : " + keyName); 
   } 
   document.onkeyup = keyUp; 

This is a clever way to explain it simply:
First of all, e = e | | event; This code is for compatibility with browser event object fetching. This code in js means that if the hidden variable e is present in FireFox or Opera, then e||event returns e, and if the hidden variable e is not present in IE, then it returns event.
Second, currKey = e.k eyCode | | e.w hich | | e.c. with our fabrication: harCode; For example, in IE, there is only the keyCode property, while in FireFox there are the which and charCode properties, and in Opera there are the keyCode and which properties.

The above code is only compatible with the browser, get the keyup event object, and simply pop up the key code and key characters, but there is a problem, when you press the key, the character keys are all uppercase, and when you press the shift key, the character display is very strange, so you need to optimize the code.

Part three: code implementation and optimization

3.1 key codes and character codes of key events

The key code and character code of key events lack the portability between browsers. For different browsers and different case events, the key code and character code are stored in different ways...
In IE, there is only one keyCode property, and its interpretation depends on the event type. For keydown, keyCode stores the keyCode, and for keypress events, keyCode stores a character code. There are no which and charCode properties in IE, so which and charCode properties are always undefined.

In FireFox, the keyCode is always 0. When the time is keydown/keyup, charCode=0, which is the keyCode. When the event keypress, which and charCode have the same value and store the character code.

In Opera, the values of keyCode and which are always the same, in the keydown/keyup event, they store the keyCode, in the keypress time, they store the character code, and charCode is not defined, it is always undefined.

3.2 use keydown/keyup or keypress

The first part has introduced the difference between keydown/keyup and keypress. There is a general rule that keydown event is the most useful for functional keys, while keypress event is the most useful for printable keys [3].

3.3 code implementation
The general idea is to use keypress event object to get key characters, and keydown event to get function characters, such as Enter, Backspace, etc.

The code implementation is shown below


!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
<HEAD><TITLE>js  Record button </TITLE> 
<META NAME="Generator" CONTENT="EditPlus"> 
<META NAME="Author" CONTENT=" Feather regression of the kernel "> 
<META NAME="Keywords" CONTENT="js  Record button "> 
<META NAME="Description" CONTENT="js  The keys   record "> 
</HEAD> 
<BODY> 
<script type="text/javascript"> 
var keystring = "";//Record the string of keys
function $(s){return document.getElementById(s)?document.getElementById(s):s;} 
function keypress(e) 
{ 
  var currKey=0,CapsLock=0,e=e||event; 
  currKey=e.keyCode||e.which||e.charCode; 
  CapsLock=currKey>=65&&currKey<=90; 
  switch(currKey) 
  { 
    //Blocked backspace, TAB, carriage return, space, direction key, delete key
    case 8: case 9:case 13:case 32:case 37:case 38:case 39:case 40:case 46:keyName = "";break; 
    default:keyName = String.fromCharCode(currKey); break; 
  } 
  keystring += keyName; 
} 
function keydown(e) 
{ 
  var e=e||event; 
  var currKey=e.keyCode||e.which||e.charCode; 
  if((currKey>7&&currKey<14)||(currKey>31&&currKey<47)) 
  { 
    switch(currKey) 
    { 
      case 8: keyName = "[ backspace ]"; break; 
      case 9: keyName = "[ TAB ]"; break; 
      case 13:keyName = "[ enter ]"; break; 
      case 32:keyName = "[ The blank space ]"; break; 
      case 33:keyName = "[PageUp]"; break; 
      case 34:keyName = "[PageDown]"; break; 
      case 35:keyName = "[End]"; break; 
      case 36:keyName = "[Home]"; break; 
      case 37:keyName = "[ The key direction of the left ]"; break; 
      case 38:keyName = "[ The direction key on the ]"; break; 
      case 39:keyName = "[ The direction key right ]"; break; 
      case 40:keyName = "[ Under the direction key ]"; break; 
      case 46:keyName = "[ delete ]"; break; 
      default:keyName = ""; break; 
    } 
    keystring += keyName; 
  } 
  $("content").innerHTML=keystring; 
} 
function keyup(e) 
{ 
  $("content").innerHTML=keystring; 
} 
document.onkeypress=keypress; 
document.onkeydown =keydown; 
document.onkeyup =keyup; 
</script> 
<input type="text" /> 
<input type="button" value=" Empty record " onclick="$('content').innerHTML = '';keystring = '';"/> 
<br/> Please press any key to see the keyboard response key value: <span id="content"></span> 
</BODY> 
</HTML> 

Code analysis:
$() : gets the dom by ID

Keypress (e) : to achieve the interception of character code, because the function keys to use the keydown, so the function keys in keypress blocked.

Keydown (e) : it mainly realizes the acquisition of function keys.

Keyup (e) : displays the intercepted string.


Related articles: