开发者

Detecting IME input before enter pressed in Javascript

I'm not even sure if this is possible, so apologies if it's a stupid question.

I've set up an keyup callback through jQuery to run a function when a user types in an input box. It works fine for Engl开发者_开发知识库ish.

However when inputting text in Japanese/Korean/Chinese, the function isn't called until the user confirms their text.

Is it possible to detect that they've started typing, and access their as-yet unfinished text?

I'm thinking maybe it's an OS-level thing so Javascript doesn't have access to it.

Edit: I just realised that this works in Chrome and Safari, but not in Firefox (not had a chance to try it on Windows yet). So Chrome calls keyup and it's possible to get the text. But I'm still having the above problem in Firefox.


The compositionstart, compositionupdate and compositionend events might be helpful. They help you detect when IME input is being used.

For example, consider using an IME to type か (ka) in Japanese.
The following events (in the order shown) would be fired:

  • k (IME visible) keydown, compositionstart, compositionupdate, compositionend, input
  • a (IME visible), compositionstart, compositionupdate, compositionend, input
  • enter (IME closed) keydown, input

Notice that the compositon events are only fired when the IME is visible (before enter is pressed). Also notice that the keypress event is not fired. This is only fired for non-IME input.

To access the user's unfinished text, you can use the data property of the event.

$('#input').on('compositionupdate', function(e) {
    console.log(e.data);
});

For more info see MDN: compositionstart, compositionupdate, compositionend, InputEvent.


This is a known issue in Firefox, and what browsers should be doing isn't clear.

A possible method for working around this problem is demonstrated here, where the text field is polled for changes to the text (rather than relying on events).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜