2
votes

I would like to emit a CtrlS keydown event using JavaScript. Ideally the solution works in most modern browsers (up to IE 9).

I am writing tests and need to test my handler for key bindings. CtrlS is just an example, it can be any key binding with a modifier key. I know about the keyEvent.initKeyboardEvent() method but I was not able to use it correctly to trigger the same event I got when printing out the full keyboard event after pressing the key from the keyboard.

2
Ctrl+S does nothing in Chrome on my MacGareth
It's a great thing that modern browsers do not allow such thing. As a user, I would really hate it to visit a web site and have my browser popup a Save As dialog automatically, don't you think?Darin Dimitrov

2 Answers

7
votes

I would like to emit a CtrlS keydown event

You mean, in order to trigger the browser's "Save as" dialog or something? That's not possible for security reasons. It would be a huge security problem if it were - imagine: every web site could arbitrarily trigger browser functions.

1
votes

You cannot and you must not for security reasons (as Pekka already pointed out). You will always require a user interaction in between. Additionally imagine the chance of the browser vendors getting sued by users, as various programmatic keyboard events will have led to spoofing attacks.

See this post for alternatives and more details. There is always the flash based copy-and-paste. Here is an elegant example. At the same time it is a testimony why the web is moving away from plugin vendors.

There is a similar security mindset applied in case of the opt-in CORS policy to access remote content programmatically.

The answer is:
There is no way to programmatically trigger input keys in the sandboxed browser environment under normal circumstances.

Bottomline: I am not saying it will not be possible in the future, under special browser-modes and/or privileges towards the end-goal of gaming, or similar user-experiences. However prior to entering such modes, the user will be asked for permissions and risks, similar to the Fullscreen API model. ( I included a google search link, as it neatly includes the relevant text lines in search-result)

enter image description here