js monitor keyboard actions

Reprinted from: http://geelong.javaeye.com/blog/810054

 

It is mainly divided into four parts . Part
1: Browser button events.
Part 2: Compatible browsers.
Part 3: Code implementation and optimization
. Part 4: Summary

 

Part 1: Browser keystroke events

    To implement keylogging with js, pay attention to the three key event types of the browser, namely keydown, keypress and keyup, which correspond to the three event handlers onkeydown, onkeypress and onkeyup respectively. A typical key press produces all three events, keydown, keypress, and then keyup when the key is released.
   Among the three event types, keydown and keyup are relatively low-level, while keypress is relatively advanced. The so-called advanced here means that when the user presses shift + 1, keypress parses the key event and returns a printable "!" character, while 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, the keypress event will not be generated, but keydown and keyup can be generated. event. However, in FireFox, function keys can generate keypress events.

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

 

Part II: Compatible Browsers

    Any js involving browsers, we must consider the issue of browser compatibility.
   Currently commonly used browsers are mainly based on IE and based on Mozilla two categories. 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 understand is how to initialize the event. The basic statement is as follows:

    function keyDown(){}
   document.onkeydown = keyDown;

When the browser reads this statement, it will call the KeyDown() function no matter which key is pressed on the keyboard.

 

2.2 Implementation of FireFox and Opera

    Programs such as FireFox and Opera are more troublesome to implement than IE, so I will describe them here first.

The keyDown() function has a hidden variable - generally, we use the letter "e" to denote this variable.

    function keyDown(e)

The variable e represents a keystroke event, to find which key was pressed, use the which property:

    e.which

e.which will give the index value of the key. The method of converting the index value into the letter or numeric value of the key needs to use the static function String.fromCharCode(), as follows:

    String.fromCharCode(e.which)

Putting the above statement together, we can get which key was pressed in FireFox:

    function keyDown(e) {
       var keycode = e.which;
       var realkey = String.fromCharCode(e.which);
       alert(”按键码: ” + keycode + ” 字符: ” + realkey);
   }
   document.onkeydown = keyDown;

 

2.3 Implementation of IE

    The IE program does not need the e variable, use window.event.keyCode to replace e.which, and convert the index value of the key to the real key value. The method is similar: String.fromCharCode(event.keyCode), the procedure is as follows:

    function keyDown() {
       var keycode = event.keyCode;
       var realkey = String.fromCharCode(event.keyCode);
       alert(”按键码: ” + keycode + ” 字符: ” + realkey);
   }
   document.onkeydown = keyDown;

 

2.4 Determine the browser type

    The above has learned how to implement the method of obtaining key event objects in various browsers. Then we need to determine the browser type. There are many methods, which are easier to understand, and there are also very clever methods. Let’s talk about the general method first: that is Using the appName property of the navigator object, of course, you can also use the userAgent property. Here, appName is used to determine the browser type. The appName of IE and Maxthon is "Microsoft Internet Explorer", while the appName of FireFox and Opera is "Netscape", so a function The simpler code is 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(”按键码: ” + keycode + ” 字符: ” + realkey);
   }
   document.onkeyup = keyUp;

 

A more concise method is [2]:

    function keyUp(e) {
       var currKey=0,e=e||event;
       currKey=e.keyCode||e.which||e.charCode;
       var keyName = String.fromCharCode(currKey);
       alert(”按键码: ” + currKey + ” 字符: ” + keyName);
   }
   document.onkeyup = keyUp;

 

    The above method is more ingenious and briefly explained:
   first, e=e||event; This code is for compatibility with browser event object acquisition. The meaning of this code in js is that if the hidden variable e exists in FireFox or Opera, then e||event returns e, and if in IE, the hidden variable e does not exist, it returns event.
   Secondly, currKey=e.keyCode||e.which||e.charCode; This sentence is to be compatible with the key code attribute of the browser key event object (see the third part for details). For example, in IE, there is only the keyCode attribute, while FireFox There are which and charCode properties, Opera has keyCode and which properties, etc.

    The above code is only compatible with the browser, obtains the keyup event object, and simply pops up the key code and the key character, but the problem arises. When you press the key, the character keys are all uppercase, and when you press the shift key, the displayed The characters are weird, so the code needs to be optimized.

 

Part 3: Code Implementation and Optimization

3.1 Key code and character code of key event

    The key codes and character codes of key events lack portability between browsers. For different browsers and different case events, key codes and character codes are stored in different ways. Key events, browsers and key event objects The attribute relationship is as follows:

[zz] javascript keyboard event full control (compatible with FireFox and IE)

    As shown in the table:

    In IE, there is only one keyCode property, and its interpretation depends on the event type. For keydown, keyCode stores the key code, and for keypress events, keyCode stores a character code. And there is no which and charCode properties in IE, so which and charCode properties are always undefined.

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

    In Opera, the value of both keyCode and which is always the same, in keydown/keyup events, they store the key code, in keypress time, they store the character code, and charCode is not defined, always undefined.

 

3.2 Use keydown/keyup or keypress

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

    Keylogging is mainly for printable characters and some function keys, so keypress is the first choice. However, as mentioned in the first part, keypress does not support function keys in IE, so it should be supplemented with keydown/keyup events.

 

3.3 The
   general idea of ​​code implementation, use the keypress event object to obtain key characters, and use the keydown event to obtain functional characters, such as Enter, Backspace, etc. The code implementation is as follows

 

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD><TITLE>js 按键记录</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="js 按键记录">
<META NAME="Description" CONTENT="js 按键记录">
</HEAD>
<BODY>

<script type=" text/javascript  ">
<!--
var  keystring = "";//Record key string

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)
   {
   //Block backspace, tab, carriage return, space, arrow keys, 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 = "[退格]"; break;
       case 9: keyName = "[制表]"; break;
       case 13:keyName = "[回车]"; break;
       case 32:keyName = "[空格]"; break;
       case 33:keyName = "[PageUp]";   break;
       case 34:keyName = "[PageDown]";   break;
       case 35:keyName = "[End]";   break;
       case 36:keyName = "[Home]";   break;
       case 37:keyName = "[Arrow key left]"; break;
       case  38:keyName = "[Arrow key up]"; break;
       case  39:keyName = "[Arrow key right]"; break;
       case  40:keyName = " [down arrow keys]"; 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="clear 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:
   $(): Obtain dom according to ID
   keypress(e): Realize the interception of character codes. Since function keys are obtained by keydown, these function keys are blocked in keypress.
   keydown(e): mainly realizes the acquisition of function keys.
   keyup(e): Displays the intercepted string.

    The code is basically finished! Ha ha

 

Part IV: Conclusion

    The original purpose of writing the code was to be able to log key presses via js and return a string.

    The above code just uses js to realize the basic English key recording. It is powerless for Chinese characters. The way I can think of to record Chinese characters is to use js, of course, to use keydown and keyup to record the underlying key events. Of course, Chinese character parsing is powerless. Of course, you can use the DOM to directly get the Chinese characters in the input, but this has left the original intention of using key events to realize key recording discussed in this article.

    The above code can also implement the function of adding a clipboard, monitoring the deletion function, and so on. . .

 

js code  copy code
  1. <script type="text/javascript">   
  2. //1   
  3. //   function keyDown(e) {   
  4. //       if(navigator.appName == "Microsoft Internet Explorer")   
  5. //       {   
  6. //           var keycode = event.keyCode;   
  7. //           var realkey = String.fromCharCode(event.keyCode);   
  8. //       }else{   
  9. //           var keycode = e.which;   
  10. //           var realkey = String.fromCharCode(e.which);   
  11. //       }   
  12. // alert("Keycode: " + keycode + " Character: " + realkey);   
  13. //   }   
  14. //   document.onkeydown = keyDown;   
  15.   
  16. //2   
  17.     function keyUp(e) {   
  18.        var  currKey=0,e=e||event;   
  19.        currKey=e.keyCode||e.which||e.charCode;   
  20.        var keyName = String.fromCharCode(currKey);   
  21.        alert( "Key code: "  + currKey +  " character: "  + keyName);   
  22.    }   
  23.    document.onkeyup = keyUp;   
  24.       
  25. </script>  

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326940052&siteId=291194637