skip to Main Content

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


  1. 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.

    // Find the search box element
    const searchBox = document.querySelector('input[name="q"]');
    
    searchBox.addEventListener('keydown', e=> console.log(e.key, e.code));
    
    pressCharKey(searchBox, 'h');
    
    function pressCharKey(input, key){
    
        if(!key?.toString().match(/^[a-z]$/i)){
            throw new Error('Not a printable alpha char');
        }
        
        const sendEvent = type => input.dispatchEvent(new KeyboardEvent(type, {
          key,
          code: 'Key' + key.toUpperCase(),
          view: window,
          bubbles: true
        }));
    
        sendEvent('keydown');
        input.value += key;
        elem.dispatchEvent(new Event('input', { bubbles:true }));
        sendEvent('keyup');
    
    }
    <input name="q"/>
    Login or Signup to reply.
  2. It uses the input event, not key events.

    const elem = document.querySelector('textarea[name="q"]');
    elem.focus();
    elem.value = 'h';
    elem.dispatchEvent(new Event('input', { bubbles:true }));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search