检测网页上的用户输入(击键或输入的事件处理)
Detecting User Input on a Web Page (Event Handling for Keystrokes or Input)
我正在创建一个基本的 chrome 扩展程序,它会在用户在网页上的任意位置键入内容时发送消息提醒。
但是,我不确定如何完成此操作,我考虑过使用 keyUp
和 keyDown
事件,但只有在事件正在监视特定字段时我才成功,而目标是检测用户可以键入的任何字段上的文本。
let timer,
timeoutVal = 1000; // time it takes to wait for user to stop typing in ms
const 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 timeout
function 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 canceled
function handleKeyUp(e) {
window.clearTimeout(timer); // prevent errant multiple timeouts from being generated
timer = window.setTimeout(() => {
status.innerHTML = 'Done';
}, timeoutVal);
}
达到预期结果的最佳方法是什么?
请记住,我正在尝试让此 chrome 扩展程序在用户在网页上键入文本或用户在文本字段内单击以开始键入时触发。
只有当用户在文本字段中没有文本并且文本字段未处于活动状态时,chrome 扩展才会消失(否则,如果文本字段中有文本,请保留扩展)。
一个选项是将事件侦听器添加到 html 元素:
document.querySelector('html').addEventListener('keypress', () => {
console.log('asd')
});
另一种选择是遍历用户可以输入的所有字段:
document.querySelectorAll('input').forEach(inp => {
inp.addEventListener('keypress', () => {console.log('asd')})
});
我正在创建一个基本的 chrome 扩展程序,它会在用户在网页上的任意位置键入内容时发送消息提醒。
但是,我不确定如何完成此操作,我考虑过使用 keyUp
和 keyDown
事件,但只有在事件正在监视特定字段时我才成功,而目标是检测用户可以键入的任何字段上的文本。
let timer,
timeoutVal = 1000; // time it takes to wait for user to stop typing in ms
const 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 timeout
function 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 canceled
function handleKeyUp(e) {
window.clearTimeout(timer); // prevent errant multiple timeouts from being generated
timer = window.setTimeout(() => {
status.innerHTML = 'Done';
}, timeoutVal);
}
达到预期结果的最佳方法是什么?
请记住,我正在尝试让此 chrome 扩展程序在用户在网页上键入文本或用户在文本字段内单击以开始键入时触发。
只有当用户在文本字段中没有文本并且文本字段未处于活动状态时,chrome 扩展才会消失(否则,如果文本字段中有文本,请保留扩展)。
一个选项是将事件侦听器添加到 html 元素:
document.querySelector('html').addEventListener('keypress', () => {
console.log('asd')
});
另一种选择是遍历用户可以输入的所有字段:
document.querySelectorAll('input').forEach(inp => {
inp.addEventListener('keypress', () => {console.log('asd')})
});