如何防止谷歌搜索自动关注按键?

时间:2016-07-13 16:54:35

标签: javascript html5 dom

我正在为自己制作扩展程序,我希望禁用自动对焦或至少在它聚焦之前运行我的功能。

我尝试在keypress, keyup, keydown, inputwindow上定位这些事件:document。并使用此停止事件:

document.addEventListener('keypress', stopEvent);

document.addEventListener('keyup', stopEvent);

document.addEventListener('keydown', stopEvent);

document.addEventListener('input', stopEvent);


document.body.addEventListener('keypress', stopEvent);

document.body.addEventListener('keyup', stopEvent);

document.body.addEventListener('keydown', stopEvent);

document.body.addEventListener('input', stopEvent);


window.addEventListener('keypress', stopEvent);

window.addEventListener('keyup', stopEvent);

window.addEventListener('keydown', stopEvent);

window.addEventListener('input', stopEvent);

function stopEvent(e) {
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault()
return false;
}

但不知何故,搜索输入框仍然被选中,我是否需要以某种方式删除所有事件处理程序?

1 个答案:

答案 0 :(得分:2)

我想通了,这是第三个参数。

useCapture https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

一些有氧运动后,我花了2分钟来解决这个问题。

function stopEvent(e) {
    e.stopImmediatePropagation();
    //e.stopPropagation();
    //e.preventDefault()
    //return false;
}

//var eles  = [window, document, document.body];
var eles  = [window];

eles.forEach(function(ele){
    ele.addEventListener('keypress',stopEvent,true);
    ele.addEventListener('keyup',stopEvent,true);
    ele.addEventListener('keydown',stopEvent,true);
    ele.addEventListener('input',stopEvent,true);
});