Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

javascript - override existing onkeydown function

My extensions go through every input entered on an on any website that is loaded.

What I do is I consider every onkeydown and manipulate it if it has some value.

my background js file contains the following:

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 = "??"; }  
}

My problem is when I have websites that already contains onkeydown function in their innerHTML webpage.

for instance:

taken from facebook's homepage:

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

the switching of node.value == 'fi' in ?? is not executing since their onkeydown="Bootloader...runs before my document.onkeydown.

How do I cause my function to run before their onkeydown is executed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of document.onkeydown = returnKey;, use

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

The most important part of this line is the third argument. When the value of this parameter is true, the event listener is triggered at capturing phase, which cannot be prevented using event.preventDefault(); or event.stopPropagation();.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...