Problem:
So I’ve been trying to get the highest possible score on the Typing test on HumanBenchmark but ran into some oddities when trying to dispatch custom keybaordEvents.
I only got it working if I captured user inputs and then dispatched them again, but I don’t understand why creating my own events won’t work. HumanBenchmark don’t seem to be checking the isTrusted flag since that is false in both scenarios.
Working code:
let vTarget = document.getElementsByClassName("letters")[0]
let vKeyEvents = {}
document.addEventListener("keydown",
function(e){
vKeyEvents[e.key] = e
}
);
function run(){
vText = vTarget.innerText
for (let index = 0; index < vText.length; index++) {
vTarget.dispatchEvent(vKeyEvents[vText[index]])
}
}
How to run my code (Demonstration):
- Goto HumanBenchmark Typing test
- Paste the above code
- Click on anything in the dom except text box
- Press every letter on your keyboard including capitals and symbols used in the text.
- type run() in the console
Code I used for creating KeyboardEvents that isn’t working
vTest = new KeyboardEvent('keydown',
{
key:"t",
keyCode:84,
isComposing: true,
view:window
});
document.getElementsByClassName("letters")[0].dispatchEvent(vTest)
Solution:
Add bubbles: true
to the KeyboardEvent
options
new KeyboardEvent('keydown',
{
key:"t",
keyCode:84,
isComposing: true,
view:window,
bubbles: true
})