JS Monitor Keyboard action

Source: Internet
Author: User
Tags printable characters

Browser Firefoxfunctionoperamicrosoftmozilla

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

Four main parts
Part I: Key events for the browser
Part Two: compatible browsers
Part III: Code implementation and optimization
Part IV: summary

Part I: Key events for the browser

Using JS to implement the keylogger, to pay attention to the browser's three types of key events, namely Keydown,keypress and KeyUp, which correspond to onkeydown, onkeypress and onkeyup three event handlers respectively. A typical button generates all three events, followed by Keydown,keypress, followed by the KeyUp when the key is released.
Of these 3 types of events, KeyDown and KeyUp are compared to the lower levels, while keypress are more advanced. The so-called advanced is that when the user presses SHIFT + 1 o'clock, KeyPress is parsing the key event to return a printable "!" characters, while KeyDown and KeyUp just recorded SHIFT + 1 for this event. [1]

However, KeyPress can only be used for some printable characters, and for function keys, such as F1-F12, Backspace, Enter, Escape, PageUP, PageDown and arrow direction, will not produce keypress events, However, KeyDown and KeyUp events can be generated. In Firefox, however, a function button can generate KeyPress events.

The event objects passed to 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 Altkey, Ctrlkey, and Shiftkey properties of the event, which are common in Firefox and IE.

Part Two: compatible browsers

Any browser-related JS, you have to consider browser-compatible issues.
Currently commonly used browsers are mainly based on IE and based on the two major categories of Mozilla. Maxthon is based on the IE kernel, while Firefox and Opera are based on the Mozilla kernel.

2.1 Initialization of the event

The first thing you need to know is how to initialize the event with the following basic statement:

function KeyDown () {}
Document.onkeydown = KeyDown;

When the browser reads this statement, the KeyDown () function is called regardless of which key on the keyboard is pressed.

2.2 How to implement Firefox and opera

Firefox and Opera are more difficult to implement than IE, so let's describe it first.

The KeyDown () function has a hidden variable-in general, we use the letter "E" to represent the variable.

function KeyDown (e)

The variable e indicates that the keystroke event occurred, and the key to be pressed to use the which property:

E.which

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

String.fromCharCode (E.which)

Put the above statement together, we can get the button which is pressed in Firefox:

function KeyDown (e) {
var keycode = E.which;
var Realkey = String.fromCharCode (E.which);
Alert ("Key code:" + KeyCode + "character:" + Realkey);
}
Document.onkeydown = KeyDown;

The realization method of 2.3 ie

IE program does not need e variables, with Window.event.keyCode to replace E.which, the key index value into the real key value method similar to: String.fromCharCode (Event.keycode), the program is as follows:

function KeyDown () {
var keycode = Event.keycode;
var Realkey = String.fromCharCode (Event.keycode);
Alert ("Key code:" + KeyCode + "character:" + Realkey);
}
Document.onkeydown = KeyDown;

2.4 Judging Browser type

The above understand how to get the key event object in a variety of browsers, then the following need to determine the browser type, this method is many, there is more convenient to understand, there is a very clever way, first of all, to say the general method: is the use of Navigator object AppName property, Of course, you can also use the UserAgent property, where appname to determine the browser type, IE and Maxthon appname is "Microsoft Internet Explorer", and Firefox and opera AppName is " Netscape ", so a simpler function of the 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 ("Key code:" + KeyCode + "character:" + Realkey);
}
Document.onkeyup = keyUp;

The 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 ("Key code:" + Currkey + "character:" + keyName);
}
Document.onkeyup = keyUp;

The above method is quite ingenious and simply explains:
First, e=e| | This code is intended for compatibility with browser event object acquisition. JS in this code means, if in Firefox or opera, the hidden variable e is present, then e| | Event returns E, if the hidden variable e is not present in IE, the event is returned.
Second, currkey=e.keycode| | e.which| | E.charcode; This is to be compatible with the key properties of the browser key event object (see the third part), IE, only the keycode attribute, and Firefox has which and CharCode properties, Opera has KeyCode and which properties.

The above code is only compatible with the browser, get the KeyUp event object, a simple pop-up key and key characters, but the problem arises, when you press the key is uppercase, and when the SHIFT key, the display of the character is very strange, so you need to optimize the code.

Part III: Code implementation and optimization

Key and character codes for 3.1 key events

Keystrokes and character codes for key events lack the portability of the browser, for different browsers and different case events, key codes and character codes are stored differently, key events, browser and key event object attributes are listed as follows:

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 key codes, and for KeyPress events, KeyCode stores a character code. The which and CharCode properties are not in IE, so the which and CharCode properties are always undefined.

Firefox keycode is always 0, time Keydown/keyup, Charcode=0,which is the key code. When the event KeyPress, the values of which and charcode are the same, and the character codes are stored.

In opera, the values of keycode and which are always the same, in the Keydown/keyup event, they store key codes, and in keypress time they store character codes, and charcode is not defined and is always undefined.

3.2 with 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 most useful for function keys, and the KeyPress event is most useful for printable keys [3].

Keylogger is mainly for printable characters and some function keys, so keypress is preferred, however, as mentioned in the first part, IE KeyPress does not support function keys, so should be supplemented with keydown/keyup events.

3.3 Implementation of the Code
General idea, use KeyPress event object to get key character, use KeyDown event to get function character, such as Enter,backspace. The code implementation is as follows

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<meta name= "Generator" content= "EditPlus" >
<meta name= "Author" content= "" >
<meta name= "Keywords" content= "JS key Record" >
<meta name= "Description" content= "JS key Record" >
</HEAD>
<BODY>

<script type= "Text/javascript" >
<!--
var keystring = "";//The string that records the key

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, 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 = "[backspace]"; Break
Case 9:keyname = "[Tabulation]"; Break
Case 13:keyname = "[carriage return]"; Break
Case 32:keyname = "[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 = "[Direction key left]"; Break
Case 38:keyname = "[on the Arrow keys]"; Break
Case 39:keyname = "[arrow key Right]"; Break
Case 40:keyname = "[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= "clears the Record" onclick= "$ (' content '). innerhtml= '; keystring= ';" />
<br/> Press any key to view keyboard response key values: <span id= "Content" ></span>
</BODY>
</HTML>

Code Analysis:
$ (): Get DOM by ID
KeyPress (E): To achieve the interception of character code, because the function keys to be obtained with KeyDown, so in the keypress to shield these function keys.
KeyDown (E): The main is to achieve the function of the button access.
KeyUp (E): Displays the intercepted string.

The code is basically even done! Oh

Part IV: summary

The original purpose of writing the code is to be able to record the key via JS and return a string.

The above code is only using JS to achieve the basic English key record, for the Chinese character is powerless, record Chinese characters, I can think of the method, of course, with JS, is used KeyDown and KeyUp record the bottom button events, Chinese character parsing is of course powerless. Of course, you can get the characters in input directly using DOM, but this has left the original intention of using key event to implement key record in this paper.

The above code can also realize the function of adding clipboard, monitoring the function of deleting and so on ...

JS 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 ("Key code:" + KeyCode + "character:" + Realkey);
  13. //   }
  14. Document.onkeydown = KeyDown;
  15. 2
  16. function keyUp (e) {
  17. var currkey=0,e=e| | Event
  18. currkey=e.keycode| | e.which| | E.charcode;
  19. var keyName = String.fromCharCode (Currkey);
  20. Alert ("key code:" + Currkey + "character:" + keyName);
  21. }
  22. Document.onkeyup = keyUp;
  23. </script>

JS Monitor Keyboard action

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.