浏览器上监听键盘操作

Database and Ruby, Python, History


这篇算是刷KPI的。写了一个油猴脚本,需要按键ctrl+k唤起,esc退出。

  const [isChatOpen, setIsChatOpen] = useState(false);

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        console.log('k key pressed');
        event.preventDefault();
        setIsChatOpen(true);
      }
      if (event.key === 'Escape') {
        console.log('esc key pressed');
        event.preventDefault();
        setIsChatOpen(false);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);