1

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);
})(); 
Intrinza
  • 11
  • 3
  • Possible duplicate of [How to trigger event in JavaScript?](http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript) – Eduardo May 16 '16 at 20:09

1 Answers1

1

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
});
Pinke Helga
  • 6,378
  • 2
  • 22
  • 42