Last night, I was working on Barra de Español and had spent quite a bit of time on Google looking for how to simulate a keypress in Firefox. It’s as simple as creating an event and dispatching it, though how to do so is not exactly intuitive. I needed to be able to do this because inserting accented characters from Barra de Español was not working in the message body textbox in Gmail and other webmail apps.
The way I inserted the characters before was to find the currently focused element, assume it was a textbox, and modify its value using the selectionStart property to know where the cursor was. Once I learned that the message body textbox could not be found using
document.commandDispatcher.focusedElement, (that’s what
if(!focused) focused = document.commandDispatcher.focusedWindow.document.activeElement; is all about) I found that the element used by Gmail for the message body wasn’t even a textbox, and didn’t have a value or selectionStart properties.
So the solution is to create a keypress event and dispatch it, like so:
var focused = document.commandDispatcher.focusedElement;
if(!focused) focused = document.commandDispatcher.focusedWindow.document.activeElement;
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, ch);
One important thing to note is that the parameter ch is not a character value, but an integer containing the character code you want to insert. So, for example, to insert the character ‘á’, ch must be the value 225. To find the values I needed I used the wonderful character lookup tool at http://entity-lookup.leftlogic.com/.
Bonus tip: If you are developing a Firefox extension and are using a text file in your profile’s extension directory to point to the folder where your code is located, and you move your code to another folder, you will discover that Firefox won’t load your extension, even though you edited the text file with the new location. The fix is to find a file in your profile directory called extensions.cache and delete it. This frustrated me for at least an hour last night, and Google failed me on this.