Question

I am trying to create a key element dynamically for my bootstrapped add-on. Currently, I create a keyset element and append it to document.getElementById('mainKeyset').parentNode with appendChild() and then create the key element (myKey) and append it to the keyset. I set the key's id, modifiers, and key attributes and then do myKey.addEventListener('command', function() {myFunction()}); to add a function to the key. After this, I can successfully call myFunction() by doing myKey.doCommand(). However, when I press the modifiers and key that I assigned in the key's attributes, nothing happens.

I am trying to avoid setting the command and oncommand attributes because I know there is a security issue with setting oncommand dynamically, but maybe I do need to use them somehow? I have seen it stated that a key can not work without command or oncommand set, so perhaps it is not possible to create a key dynamically without setting one of them. My event listener works if I set oncommand to "void(0);" (following the example given here). However, I don't know if something like that could get pass Mozilla's extension approval process.

Was it helpful?

Solution

The statement about <key> elements requiring either a command or an oncommand attribute is correct. Looking at the code triggering key handlers, it has an optimization that will ignore any <key> element that is either disabled or has neither a command nor an oncommand attribute - so the command event won't even fire for these elements. I solve this by adding a dummy oncommand attribute containing a JavaScript comment:

key.setAttribute("oncommand", "//");

But void(0); is fine as attribute value as well of course.

There won't be any issues getting this reviewed. The potential security issue you heard about is generating oncommand value dynamically, e.g.:

key.setAttribute("oncommand", "foo('" + bar + "')");

Depending on the value of bar (and particularly when bar comes from a website) this can be very dangerous. However, you don't generate the attribute value dynamically, it's always void(0); in your case - so no issue there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top