I would like to know how to get a certain key on the keyboard to be pressed via code on nodejs.
For instance, I want the f3 button to pressed once the following page is rendered:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// press key
});
module.exports = router;
Take a look at robotjs, which can be used to generate keyboard events.
For instance, to "send" an F3 key press:
const robot = require('robotjs');
...
router.get('/', function(req, res, next) {
robot.keyTap('f3');
res.end();
});
Although it depends on which OS you're using if this is going to work as expected.
Not possible from server side. You can include a javascript script in your page which can trigger the event. If you are using jQuery.
var ev = jQuery.Event("keypress");
ev.ctrlKey = false;
ev.which = 37;
$("container").trigger(ev);
Is it possible to trigger a keyboard button with JavaScript?
You can simply use applescript in nodejs, and node-key-sender on other platform.
const os = require('os')
const childProcess = require('child_process')
const { promisify } = require('util')
const ks = require('node-key-sender')
function hitHotkey (key, modifier) {
if (os.type() === 'Darwin') {
if (modifier) {
return exec(`Script="tell app \\"System Events\\" to keystroke ${key} using ${modifier} down"
osascript -e "$Script"`)
} else {
return exec(`Script="tell app \\"System Events\\" to keystroke ${key}"
osascript -e "$Script"`)
}
} else {
if (modifier) {
return ks.sendCombination([modifier, key])
} else {
return ks.sendKey(key)
}
}
}