Home Web Front-end JS Tutorial js keylogging implementation (compatible with FireFox and IE)_javascript skills

js keylogging implementation (compatible with FireFox and IE)_javascript skills

May 16, 2016 pm 06:35 PM
js

主要分四个部分
第一部分:浏览器的按键事件
第二部分:兼容浏览器
第三部分:代码实现和优化
第四部分:总结

第一部分:浏览器的按键事件

用js实现键盘记录,要关注浏览器的三种按键事件类型,即keydown,keypress和keyup,它们分别对应onkeydown、onkeypress和onkeyup这三个事件句柄。一个典型的按键会产生所有这三种事件,依次是keydown,keypress,然后是按键释放时候的keyup。

在这3种事件类型中,keydown和keyup比较底层,而keypress比较高级。这里所谓的高级是指,当用户按下shift + 1时,keypress是对这个按键事件进行解析后返回一个可打印的“!”字符,而keydown和keyup只是记录了shift + 1这个事件。[1]

但是keypress只能针对一些可以打印出来的字符有效,而对于功能按键,如F1-F12、Backspace、Enter、Escape、PageUP、PageDown和箭头方向等,就不会产生keypress事件,但是可以产生keydown和keyup事件。然而在FireFox中,功能按键是可以产生keypress事件的。

传递给keydown、keypress和keyup事件句柄的事件对象有一些通用的属性。如果Alt、Ctrl或Shift和一个按键一起按下,这通过事件的altKey、ctrlKey和shiftKey属性表示,这些属性在FireFox和IE中是通用的。

第二部分:兼容浏览器

凡是涉及浏览器的js,就都要考虑浏览器兼容的问题。
目前常用的浏览器主要有基于IE和基于Mozilla两大类。Maxthon是基于IE内核的,而FireFox和Opera是基于Mozilla内核的。

2.1 事件的初始化

首先需要了解的是如何初始化该事件,基本语句如下:

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

当浏览器读到这个语句时,无论按下键盘上的哪个键,都将呼叫KeyDown()函数。

2.2 FireFox和Opera的实现方法

FireFox和Opera等程序实现要比IE麻烦,所以这里先描述一下。

keyDown()函数有一个隐藏的变量--一般的,我们使用字母“e”来表示这个变量。  
  
function keyDown(e)   
  
变量e表示发生击键事件,寻找是哪个键被按下,要使用which这个属性:  
  
e.which   
  
e.which将给出该键的索引值,把索引值转化成该键的字母或数字值的方法需要用到静态函数String.fromCharCode(),如下:  
  
String.fromCharCode(e.which)   
  
把上面的语句放在一起,我们可以在FireFox中得到被按下的是哪一个键:  
  
function keyDown(e) {  
        var keycode = e.which;  
    var realkey = String.fromCharCode(e.which);  
    alert("按键码: " + keycode + " 字符: " + realkey);  
    }
   document.onkeydown = keyDown;

2.3 IE的实现方法

IE的程序不需要e变量,用window.event.keyCode来代替e.which,把键的索引值转化为真实键值方法类似:String.fromCharCode(event.keyCode),程序如下:  
  
     function keyDown() {  
      var keycode = event.keyCode;  
      var realkey = String.fromCharCode(event.keyCode);  
          alert("按键码: " + keycode + " 字符: " + realkey);  
      
     document.onkeydown = keyDown;

2.4 判断浏览器类型

上面了解了在各种浏览器里是如何实现获取按键事件对象的方法,那么下面需要判断浏览器类型,这个方法很多,有比较方便理解的,也有很巧妙的办法,先说一般的方法:就是利用navigator对象的appName属性,当然也可以用userAgent属性,这里用appName来实现判断浏览器类型,IE和Maxthon的appName是“Microsoft Internet Explorer” ,而FireFox和Opera的appName是“Netscape”,所以一个功能比较简单的代码如下:

       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;

比较简洁的方法是[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;

上面这种方法比较巧妙,简单地解释一下:
首先,e=e||event;这句代码是为了进行浏览器事件对象获取的兼容。js中这句代码的意思是,如果在FireFox或Opera中,隐藏的变量e是存在的,那么e||event返回e,如果在IE中,隐藏变量e是不存在,则返回event。
其次,currKey=e.keyCode||e.which||e.charCode;这句是为了兼容浏览器按键事件对象的按键码属性(详见第三部分),如IE中,只有keyCode属性,而FireFox中有which和charCode属性,Opera中有keyCode和which属性等。

上述代码只是兼容了浏览器,获取了keyup事件对象,简单的弹出了按键码和按键的字符,但是问题出现了,当你按键时,字符键都是大写的,而按shift键时,显示的字符很奇怪,所以就需要优化一下代码了。

第三部分:代码实现和优化

3.1 按键事件的按键码和字符码

按键事件的按键码和字符码缺乏浏览器间的可移植性,对于不同的浏览器和不同的案件事件,按键码和字符码的存储方式都是不同的,按键事件,浏览器和按键事件对象属性关系如下表:

 

如表所示:

在IE中,只有一个keyCode属性,并且它的解释取决于事件类型。对于keydown来说,keyCode存储的是按键码,对于keypress事件来说,keyCode存储的是一个字符码。而IE中没有which和charCode属性,所以which和charCode属性始终为undefined。

FireFox中keyCode始终为0,时间keydown/keyup时,charCode=0,which为按键码。事件keypress时,which和charCode二者的值相同,存储了字符码。

在Opera中,keyCode和which二者的值始终相同,在keydown/keyup事件中,它们存储按键码,在keypress时间中,它们存储字符码,而charCode没有定义,始终是undefined。

3.2 用keydown/keyup还是keypress

第一部分已经介绍了keydown/keyup和keypress的区别,有一条比较通用的规则,keydown事件对于功能按键来说是最有用的,而keypress事件对于可打印按键来说是最有用的[3]。

键盘记录主要是针对于可打印字符和部分功能按键,所以keypress是首选,然而正如第一部分提到的,IE中keypress不支持功能按键,所以应该用keydown/keyup事件来进行补充。

3.3 代码的实现
总体思路,用keypress事件对象获取按键字符,用keydown事件获取功能字符,如Enter,Backspace等。

代码实现如下所示

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

js keystroke logging










Please Press any key to view the keyboard response key value:

Code analysis:
$(): Obtain dom according to ID
keypress(e): Implement the interception of character codes. Since the function keys need to be obtained using keydown, these function keys are blocked in keypress.
keydown(e): Mainly realizes the acquisition of function keys.
keyup(e): Display the intercepted string.

The code is basically completed! Haha

Part 4: Summary

The original purpose of writing the code is to be able to record keystrokes through js and return a string.

The above code only uses js to implement basic English keystroke recording. It is powerless for Chinese characters. The only way I can think of to record Chinese characters is, of course, to use js, which is to use keydown and keyup to record underlying keystroke events. Of course, there is nothing that can be done about Chinese character analysis. Of course, you can directly obtain the Chinese characters in the input using DOM, but this has departed from the original intention of using key events to achieve key recording discussed in this article.

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

Quote:

[1] "The Authoritative Guide to JavaScript", fifth edition O'REILLY Press/Mechanical Industry Press, 424 pages
[2] "The Authoritative Guide to JavaScript," fifth edition O'REILLY Press/Machinery Industry Press, pages 427
[3] "The Authoritative Guide to JavaScript" Fifth Edition O'REILLY Press/Machinery Industry Press 425 pages

Appendix:

Key list corresponding to commonly used key codes:

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles