Filipe Silva
Filipe Silva

Reputation: 21657

Simulate a Keystroke in Firefox addon

I want to be able to simulate a keystroke from my firefox-addon and at the moment I'm not being able to do that.

I found this post Why simulation of Left Arrow + Shift keys doesnt work in Firefox? and my code is almost the same, but it only does the focus part, not the dispatchEvent. Any idea why this could be happening?

Here is the code:

objTag.focus();
var e = document.createEvent('KeyboardEvent');
e.initKeyEvent('keydown', true, true, window, false, false, false, false, 35, 0);
objTag.dispatchEvent(e);

Upvotes: 6

Views: 3840

Answers (1)

Wladimir Palant
Wladimir Palant

Reputation: 57651

Your code is correct but the <textarea> element reacts to keypress events, not keydown.

Anyway, why so complicated? You can just set input.value and then use input.setSelectionRange() method to move the cursor appropriately. If you want to add something to the end of the current line you would do it like this:

var position = objTag.selectionStart;
var lineEnd = objTag.value.indexOf("\n", position);
if (lineEnd < 0) // No more line breaks
  lineEnd = objTag.value.length;

var textToAdd = "foo";
objTag.value = objTag.value.substr(0, lineEnd) + textToAdd + objTag.value.substr(lineEnd);
objTag.setSelectionRange(lineEnd + textToAdd.length, lineEnd + textToAdd.length);
objTag.focus();

Adding to the end of the text is even simpler:

var textToAdd = "foo";
objTag.value += textToAdd;
objTag.setSelectionRange(objTag.value.length, objTag.value.length);
objTag.focus();

Upvotes: 2

Related Questions