You can do it as follows -
// Setup the eventListener to log whenever a key press occurs
window.addEventListener('keydown', function(event) {
console.log('key pressed - ', event.key);
});
// create a keyboard press event
var event = new KeyboardEvent('keydown', {
'key': '1'
});
// call / simulate the event every 1000s using dispathEvent method
setInterval(() => window.dispatchEvent(event), 1000);
In the above demo code, I have just set an eventListener
over the whole window which would just console log - key pressed
whenever a key is pressed.
Below it is just creating an event using new KeyboardEvent
and then calling it or you can say simulating a keyboard press event every 1 second using dispatchEvent
inside the setInterval
function