I want to create a test script which types letter h and it should show suggestions. But below code is doing nothing
I am trying this
// Find the search box element
let searchBox = document.querySelector('input[name="q"]');
// Create a KeyboardEvent for "keydown" event
let keyDownEvent = new KeyboardEvent('keydown', {
key: 'h',
code: 'KeyH',
keyCode: 72,
view: window,
bubbles: true
});
// Dispatch the "keydown" event
searchBox.dispatchEvent(keyDownEvent);
// Create a KeyboardEvent for "keyup" event
let keyUpEvent = new KeyboardEvent('keyup', {
key: 'h',
code: 'KeyH',
keyCode: 72,
view: window,
bubbles: true
});
// Dispatch the "keyup" event
searchBox.dispatchEvent(keyUpEvent);
Can you suggest if I am missing any other events or anything is wrong here.
I am using Chrome console to run this and getting true as response.
I found what events are hitting when we type any letter events are keyDown, KeyPress, inputTest, input & keyUp.
I tried all in once script & keyDown & keyUp as well. but Nothing worked
2
Answers
Triggering keyboard events doesn’t actually fills the input with proper characters. Fill it manually and spice up with
input
event. Also configure the keyboard event to your taste. You should know what your suggestion code relies on and provide all needed data. So if the suggestion code relies on the value inside the search box the value should be provided. Just dive inside the suggestion code and step-debug it.It uses the input event, not key events.