我正在創建一個基本的 Chrome 擴展,當用戶在網頁上的任何位置鍵入時,它會發送消息提醒。但是,我不確定如何實現這一點,我考慮過使用keyUp和keyDown事件,但只有當事件正在監視特定字段時我才成功,而目標是檢測用戶可以鍵入的任何字段上的文本。let timer, timeoutVal = 1000; // time it takes to wait for user to stop typing in msconst status = document.getElementById('status');const typer = document.getElementById('typer');typer.addEventListener('keypress', handleKeyPress);typer.addEventListener('keyup', handleKeyUp);// when user is pressing down on keys, clear the timeoutfunction handleKeyPress(e) { window.clearTimeout(timer); status.innerHTML = 'Typing...';}// when the user has stopped pressing on keys, set the timeout// if the user presses on keys before the timeout is reached, then this timeout is canceledfunction handleKeyUp(e) { window.clearTimeout(timer); // prevent errant multiple timeouts from being generated timer = window.setTimeout(() => { status.innerHTML = 'Done'; }, timeoutVal);}達到預期結果的最佳方法是什么?請記住,我試圖在用戶在網頁上輸入文本或用戶單擊文本字段內部開始輸入時觸發此 chrome 擴展。僅當用戶在文本字段中沒有文本且文本字段未處于活動狀態時,chrome 擴展才應消失(否則,如果文本字段中有文本,則保留擴展)。
檢測網頁上的用戶輸入(擊鍵或輸入的事件處理)
眼眸繁星
2023-12-14 15:44:13