Is it possible to simulate keyboard/mouse event in NodeJS?

后端 未结 5 1906
别跟我提以往
别跟我提以往 2020-12-06 10:07

Imagine that a NodeJS module, when invoked from console, outputs some introductory messages and then waits for user input (click enter or esc). This module already has and d

相关标签:
5条回答
  • 2020-12-06 10:52

    As Jason mentioned you could use RobotJS for key simulation but there are couple of steps require to correctly build robotJS for Windows paltform:

    1. You would need windows build tools so run npm install --global windows-build-tools (would take some time as it's around 120MB)
    2. run npm install robotjs --save-dev
      You're done!.
      If this is for electron app then you would also require below 3rd step:
    3. run npm rebuild --runtime=electron --target=1.7.9 --disturl=https://atom.io/download/atom-shell --abi=57

      (1.7.9 is my electron --version and abi is for my corresponding node --version 8.7 installed, you can check abi version for node version here [look for NODE_MODULE_VERSION column])

    0 讨论(0)
  • 2020-12-06 10:56

    I've tried robotjs and node-key-sender, but they cause a substantial amount of delay/stuttering per key-event. (especially noticeable when sending them frequently)

    To resolve this, I found a way to use node-ffi-napi to call the Windows user32 SendInput function directly: https://stackoverflow.com/a/50412529/2441655

    In my case at least, this achieved substantially better performance. (however, a drawback is that it only works on Windows, of course)

    0 讨论(0)
  • 2020-12-06 11:02

    node-key-sender library is an alternative to RobotJs if you just need to send keys to your operational system. It is cross platform and very small lib.

    Install it with npm install --save-dev node-key-sender.

    And send "enter" to the keyboard using:

    var ks = require('node-key-sender');
    ks.sendKey('enter');
    

    Check out the documentation page: https://www.npmjs.com/package/node-key-sender.

    0 讨论(0)
  • 2020-12-06 11:05

    Responding to @Venryx. They are right that robotjs is going to have a delay, especially if you have to load node first, however, if you already have node loader, it may be worth trying out

    robot.setKeyboardDelay(0)
    

    The default setting for a delay is 10ms. This helped me tremendously.

    0 讨论(0)
  • 2020-12-06 11:10

    You could use possibly use RobotJS for this.

    Example code:

    var robot = require("robotjs");
    
    // Type user's password or something. 
    robot.typeString("abc123");
    
    0 讨论(0)
提交回复
热议问题