覆盖现有的onkeydown函数

6

我的扩展程序会检查加载的任何网站上的所有输入内容。

我会考虑每个onkeydown事件,并在其具有某些值时进行操作。

我的background js文件包含以下内容:

document.onkeydown = returnKey; 

function returnKey(evt) {   
    var evt  = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);  
    if ( node.value == 'fi' ) { evt.srcElement.value = "??"; }  
}

我的问题是,当我有一些网站在其innerHTML网页中已经包含onkeydown函数时。

例如:

从Facebook主页上摘录:

<textarea class="uiTextareaAutogrow input" onkeydown="Bootloader.loadComponents([&quot;control-textarea&quot;], function() { TextAreaControl.getInstance(this) }.bind(this));

在 ?? 中,node.value == 'fi' 的切换没有执行,因为它们的 onkeydown="Bootloader... 在我的 document.onkeydown 之前运行。如何使我的函数在他们的 onkeydown 执行之前运行?
1个回答

9

不要使用document.onkeydown = returnKey;,而应该使用

document.addEventListener('keydown', returnKey, true);

这行代码最重要的部分是第三个参数。当此参数的值为true时,事件监听器在捕获阶段被触发,无法使用event.preventDefault();event.stopPropagation();阻止它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接