I am thinking about making a Firefox add-on of my own and doing some experiments for the functionality I might be adding in it.
As I am just checking the feasibility of things for now, I just got a skeleton created from Mozilla add-on builder and started working in it. What I am trying right now is to send mouse click or key press events.
I have tried the available ways to send event but somehow it's not working for key events
I tried it using dispatchEvent:
onMenuItemCommand: function(e) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var evt1 = document.createEvent("MouseEvents");
evt1.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
//it's returning me null for document.getElementById... so I changed it.
var cb1 = gBrowser.selectedBrowser.contentDocument.getElementById("strict");
var canceled1 = !cb1.dispatchEvent(evt1);
var evt = document.createEvent("KeyEvents");
evt.initKeyEvent("keydown", true, false, window,
false, false, false, false, 0x42, 0);
var cb = gBrowser.selectedBrowser.contentDocument.getElementById("filter");
var canceled = !cb.dispatchEvent(evt);
if(canceled)
{
// A handler called preventDefault
alert("canceled");
}
else
{
// None of the handlers called preventDefault
alert("not canceled");
}
}
When I tried this code in Firefox, it did updated the checkbox which means click event worked, but nothing happened in textbox where I was expecting it to print a character. But it showed alert box with "not Cancelled" proving that event was not cancelled!
As event was not cancelled, I decided to put a keypressed handler on window.document... and it got invoked when add-on send these events! Which means the events are getting generated and are bubbling as well.
Then why only mouse events are working and key events are not? Am I missing something here?
(I have also tried sendKeyEvent with nsIDOMWindowUtils. still had no luck with it.)
btw, I am using Firefox 3.6.15 with Gecko :1.9.2.15
You have to focus the element before you can dispatch a key event to it.
EDIT:
This is only true for web pages. Extensions can dispatch keypress events to any text field.
EDIT:
Text entry is done via keypress events, not keydown events.
EDIT:
You won't get any characters inserted if you don't provide a character code. (Sorry for overlooking that, it should have been obvious.) Also although it seems to work with your window you should pass in the browser's contentWindow as the defaultView.