Intrinza
Intrinza

Reputation: 11

Press a different key multiple times when one key is pressed?

So what I'm doing is when the key "e" is pressed on a certain website then it will press the key "w" multiple times. I did tests to see if it the script gets to the point where it presses "e" with an alert(); and it worked, but it doesn't trigger the key "w".

// @run-at       document-end
// ==/UserScript==

(function() {
var amount = 6;
var duration = 50; //ms

var overwriting = function(evt) {
    if (evt.keyCode === 69) { // KEY_E
        for (var i = 0; i < amount; ++i) {
            setTimeout(function() {
                alert("Key e is pressed"); /* This works */
                window.onkeydown({keyCode: 87}); // KEY_W /* This doesn't */
                window.onkeyup({keyCode: 87});
            }, i * duration);
        }
    }
};
window.addEventListener('keydown', overwriting);
})(); 

Upvotes: 1

Views: 416

Answers (1)

Pinke Helga
Pinke Helga

Reputation: 6682

You are calling the legacy event listener directly. Actually it will be executed, if it exists. However, this can not trigger a registered event listener (by addEventListener()). To do so, trigger an event to the desired target (e.g. window) and let the browser do anything else.

window.dispatchEvent(new KeyboardEvent('keydown', 
{
  'view': window,
  'which': 87,
  'keyCode': 87,
  'bubbles': true,
  'cancelable': true
});

Upvotes: 1

Related Questions