


javascript key event (compatible with all browsers)_javascript skills
Part 1: Browser key events
To implement keylogging using js, you should pay attention to the three key event types of the browser, namely keydown, keypress and keyup, which correspond to the three event handles onkeydown, onkeypress and onkeyup respectively. A typical keypress will generate all three events, in order keydown, keypress, and then keyup when the key is released.
Among these 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 only record the shift 1 event. [1]
But keypress is only effective for some characters that can be printed. For function keys, such as F1-F12, Backspace, Enter, Escape, PageUP, PageDown and arrow direction, the keypress event will not be generated, but it can be generated. keydown and keyup events. However, in FireFox, function keys can generate keypress events.
The event objects passed to keydown, keypress and keyup event handlers have some common properties. If Alt, Ctrl, or Shift are pressed together with a key, this is represented by the event's altKey, ctrlKey, and shiftKey properties, which are common to FireFox and IE.
Part 2: Compatible Browsers
Any js that involves browsers must consider browser compatibility issues.
Currently commonly used browsers are mainly based on IE and Mozilla. Maxthon is based on the IE kernel, while FireFox and Opera are based on the Mozilla kernel.
2.1 Event initialization
The first thing you need to know is how to initialize the event. The basic statement is as follows:
Function keyDown(){}
document.onkeydown = keyDown;
When the browser reads this statement, no matter which key on the keyboard is pressed, the KeyDown() function will be called.
2.2 Implementation methods 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 represent this variable.
Function keyDown(e)
The variable e represents a keystroke event. To find which key was pressed, use the which attribute:
e.which
e.which will give the index value of the key. To convert the index value into the alphanumeric value of the key, you need to use the static function String.fromCharCode(), as follows:
String.fromCharCode(e.which)
Putting the above statements 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: " keycode " Character: " realkey);
}
document.onkeydown = keyDown;
2.3 Implementation method of IE
The IE program does not need the e variable. Use window.event.keyCode instead of e.which. The method of converting the key index value into the real key value is similar: String.fromCharCode(event.keyCode). The program is as follows:
function keyDown() {
var keycode = event.keyCode ;
var realkey = String.fromCharCode(event.keyCode);
alert("Keycode: " keycode " character: " realkey);
}
document.onkeydown = keyDown;
2.4 Determine browser type
We have learned above how to obtain key event objects in various browsers. Now we need to determine the browser type. There are many methods, some are easier to understand, and some are very clever. Let’s talk about the general ones first. Method: Use the appName attribute of the navigator object. Of course, you can also use the userAgent attribute. 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 code with a relatively simple function 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; "Keycode: " keycode " Character: " realkey);
}
document.onkeyup = keyUp;
The simpler method is [2]:
Copy code
}
document.onkeyup = keyUp;
The above method is more ingenious. Let’s explain it briefly:
First, e=e||event; this 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. If the hidden variable e does not exist in IE, then event is returned.
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 Part 3 for details). For example, in IE, there is only the keyCode attribute. , while FireFox has which and charCode attributes, Opera has keyCode and which attributes, etc.
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, the storage methods of key codes and character codes are different... .In IE, there is only one keyCode attribute, and its interpretation depends on the event type. For keydown, keyCode stores the key code. For keypress events, keyCode stores a character code. There are no which and charCode attributes in IE, so the which and charCode attributes are always undefined. The keyCode in FireFox is always 0. When the time is keydown/keyup, charCode=0, which is the key code. When the event keypress occurs, the values of which and charCode are the same, and the character code is stored.
In Opera, the values of keyCode and which are always the same. In the keydown/keyup event, they store the key code. In the keypress time, they store the character code, and charCode is not defined and is always undefined.
3.2 Should I use keydown/keyup or keypress
The first part has introduced the difference between keydown/keyup and keypress. There is a general rule that the keydown event is the most useful for function keys, while the keypress event is the most useful for printable keys [3 ].
Keyboard logging is mainly for printable characters and some function keys, so keypress is the first choice. However, as mentioned in the first part, keypress in IE does not support function keys, so keydown/keyup events should be used to supplement it.
3.3 Code implementation
The general idea is to use the keypress event object to obtain key characters, and use the keydown event to obtain function characters, such as Enter, Backspace, etc.
The code implementation is as follows
Copy the code

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
