Skip to content

Instantly share code, notes, and snippets.

@tualatrix
Created December 16, 2024 05:28
Show Gist options
  • Save tualatrix/1ae65f6dd304874a23b70b2b469689bc to your computer and use it in GitHub Desktop.
Save tualatrix/1ae65f6dd304874a23b70b2b469689bc to your computer and use it in GitHub Desktop.
Fix CJK IME Enter Issue on Claude.ai
// ==UserScript==
// @name Fix CJK IME Enter Issue on Claude.ai (Extended Blocking)
// @namespace https://claude.ai/
// @version 0.6
// @description Block Enter across keydown/keypress/keyup, use stopImmediatePropagation, and a short time window after compositionend.
// @match https://claude.ai/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let imeActive = false;
let imeRecentlyEnded = false;
let imeTimeout = null;
// 监听输入法事件
document.addEventListener('compositionstart', (e) => {
imeActive = true;
}, true);
document.addEventListener('compositionend', (e) => {
imeActive = false;
imeRecentlyEnded = true;
if (imeTimeout) clearTimeout(imeTimeout);
imeTimeout = setTimeout(() => {
imeRecentlyEnded = false;
}, 200); // 稍微延长时间窗口为 200ms
}, true);
// 定义一个事件处理函数,覆盖 keydown/keypress/keyup
const handleKeyEvent = (e) => {
const isEnter = (e.key === 'Enter' || e.keyCode === 13);
const isIOSComposition = (e.keyCode === 229); // iOS IME Enter often gives code=229
const shouldBlock = isEnter && (imeActive || imeRecentlyEnded || isIOSComposition);
if (shouldBlock) {
e.preventDefault();
e.stopPropagation();
if (e.stopImmediatePropagation) {
e.stopImmediatePropagation();
}
}
};
// 对 keydown/keypress/keyup 都进行捕获阶段监听
window.addEventListener("keydown", handleKeyEvent, true);
})();c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment