It appears that the cause of this bug is the same as for Pressing <Enter> in an input method editor should not submit comments, which affects IME users on various browsers, not just Firefox.
In both cases, the problem is that the event handler that the Stack Exchange UI uses to trigger comment form submission via the enter key is, for some peculiar reason, set to trigger on the keyup
event rather than, as one would expect, on the keydown
event.
The problem here is that, if pressing enter causes focus to transfer from some other UI element (such as a context menu) to the comment entry textarea, then the keyup
event will be dispatched to the textarea, rather than to whatever element previously had the focus (which might not even exist anymore). This is, in fact, correct behavior according to the W3C DOM events specification:
"Note: The event target might change between different key events. For example, a keydown event for the 'Tab' key will likely have a different event target than the keyup event on the same keystroke."
(Actually, I recall seeing a much more explicit note about this behavior somewhere, but I can't track it down right now.)
Anyway, the right way to fix this is simply to attach the handler to the keydown
event instead. If that event fires on the textarea, we can be sure that the user actually did press the key while the focus was in the textarea.
In fact, while waiting for a proper fix from the SE devs, I've implemented a fix for this issue in the Stack Overflow Unofficial Patch using the following code:
StackExchange.helpers.submitFormOnEnterPress = function ($form) {
var $txt = $form.find('textarea');
$txt.keydown(function (event) {
if (event.which === 13 && !event.shiftKey && !$txt.prev("#tabcomplete > li:visible").length) {
$form.submit();
}
}).keypress(function (event) {
// disable hitting enter to produce a newline, but allow <shift> + <enter>
return event.which !== 13 || event.shiftKey;
});
};
This overrides the built-in SE code to enable submit-on-enter behavior in the comment editor, replacing it with a modified version that reacts to keydown
events instead of keyup
events. As far as I can tell, this fixes the issue described above, and also allows IMEs to work properly without requiring any composition event tricks.
javascript:
URL that contains an error also submits the comment (at least in Firefox).keydown
event is issued when pressing Enter anyway, even in a context menu.