For those who want to do this in pure javascript, look at:
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);