I was wondering if and how it's possible to simulate key presses in JavaScript in non-standard scenarios; for example, how would I dispatch a "left arrow keypress" event in Google's snake game? Or, perhaps, write out and send a message on Discord? It seems that most of the solutions do dispatch the event (they set off the "onkeydown" or "onkeypress" functions), but nothing is actually typed. What I'm really looking for here is to directly simulate a keypress in whatever is currently focused on. All of the answers that I've found require directly selecting the element to dispatch the event on, but this doesn't work in these non-standard cases because it's not clear what element needs to be focused on to begin with.
I could use Robot.js to simulate these key presses, but in some cases this is not an option (for example, if I wanted to make a snake bot, pulling canvas data is much easier in the browser than with Node.js, since functions already exist to make this possible. Using the browser and Node.js would require some form of cross-communication, which would be slow and a pain to setup). I suppose I'm looking for something that acts like Robot.js (for keypresses), but is usable within the browser.
Hopefully this question makes sense; thanks in advance :)