Skip to content

Send input javascript, on Chrome

Does someone have any idea why only the second time I run my code it does work?

ThisElement = document.querySelector("#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text");

ThisElement.innerText = 'message';

var focusEvent = new FocusEvent('focus', {
  bubbles: false,
  cancelBubble: false,
  cancelable: false,
  composed: true,
  currentTarget: null,
  defaultPrevented: false,
  detail: 0,
  eventPhase: 0,
  isTrusted: true,
});

ThisElement.dispatchEvent(focusEvent);

https://youtu.be/yrD9jB1FXHo

The code just sends a message in the search box.

I’m testing it on chrome using the DevTools console (F12).

Answer

The problem is with the React JS used to design whatsapp web, so to manage this you can call again event in the setTimeout

Reason behind this issue: On the first event trigger the whatsapp web screen will release all the input focused from the app screen, so it is required to again trigger event to stimulate human action in browser.

        function searchContact(contact_name = "") {
        search = document.querySelector('#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text');

        var focusEvent = new FocusEvent('focus', {
            bubbles: true,
            cancelBubble: false,
            cancelable: true,
            composed: true,
            currentTarget: null,
            defaultPrevented: false,
            detail: 0,
            eventPhase: 0,
            isTrusted: true,
        });

        //Enter value in search box events
        var inputEvent = new InputEvent('input', {
            bubbles: true
        });

        search.textContent = contact_name;
        search.dispatchEvent(focusEvent);
        search.dispatchEvent(inputEvent);


        setTimeout(function() {

            search.textContent = contact_name;
            search.dispatchEvent(focusEvent);
            search.dispatchEvent(inputEvent);
        
            el = document.querySelector("#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text");
            var event = new KeyboardEvent('keydown', {
                code: 'Enter',
                key: 'Enter',
                keyCode: 13,
                view: window,
                bubbles: true
            });

            el.dispatchEvent(event);
            
        }, 1000)

    }

    searchContact("name");
    
    function triggerMouseEvent(el, etype) {
        console.log(el)
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent(etype, true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
        el.dispatchEvent(evt);
    }