IME利用者のEnterが暴発しないようにisComposingで防ぐ
海外製Webサービスを利用すると、日本語変換の確定時(Enter押下時)に入力途中のデータがSubmitされてしまうことが多々ある。GitHubのIssue/PRのタイトルしかり、ChatGPTの入力欄しかり。
Enterでフォームを送信するのはWebの標準的な挙動だが、IME利用者(主に日本/韓国/中国語話者など)にとって非常に不便なので変換確定時のEnterのイベントを無効化する処理が必要になる。
そんなときに使えるのがKeyboardEvent.isComposingやElement#compositionstartイベント、Element#compositionendイベントだ。
<form>
<label for="title">Title</label>
<input id="title" type="text" />
</form>
document
.querySelector('#title')
.addEventListener('keydown', e => {
if (e.code !== 'Enter') {
return
}
// 変換中のEnterを無効化
if (e.isComposing) {
e.preventDefault()
return
}
submit(e.target.value)
})
また、compositionstartやcompositionendイベントを利用することで、変換中かどうかをフラグ管理できる。IME利用中はUIを変えることもできる。
let isComposing = false
const input = document.querySelector('#title')
input.addEventListener('compositionstart', () => {
isComposing = true
})
input.addEventListener('compositionend', () => {
isComposing = false
})