Please input JavaScript into Chrome

Can anyone explain why my code only works correctly the second time it's run?

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 purpose of this code is to input a message in the search box.

I'm running the test on Chrome using the DevTools console (F12).

Answer №1

To address the issue with React JS used in designing whatsapp web, it is recommended to recall the event within setTimeout for effective management.

Explanation of the problem: Upon the initial event triggering, the whatsapp web screen will release all input focus from the app screen, necessitating a repeated event trigger to simulate human interaction in the browser.

        function executeSearch(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,
        });

        // Events for entering value in search box
        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)

    }

    executeSearch("name");
    
    function invokeMouseEvent(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);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an installation package for an Electron application on Windows

Is it possible to create a Mac installer for an Electron app using a Windows PC? I have tried running npm make, but it only generates a Windows installer. ...

What is the best way to show a macOS progress pie loading icon alongside files?

While using macOS, a pie loading icon appears next to a file during downloading or transferring. To illustrate, here is an example of a file being downloaded from Chrome: https://i.sstatic.net/8jS4X.png I am interested in implementing a similar feature i ...

What is the best way to pass the JWT token to the subsequent page once a user has successfully logged in on Next.js?

Introduction I am currently working on a login application using Nextjs for the frontend and Spring Boot for the backend. Issue The problem I am facing is that after successfully logging in from the frontend, which calls the /authenticate login API devel ...

I created a thorough duplicate that successfully addressed an issue with a table

Currently, I am facing an issue with the material-table library as it automatically adds a new element called tableData to my object when I update it using Patch in my code and API. To resolve this problem, I tried implementing both a conventional and cust ...

The proper way to link various asynchronous operations enclosed in promises

My current understanding of promises is that they serve as a wrapper for async functions within the outer environment (such as the browser or node.js). However, I am struggling with how to properly connect async operations using promises in software develo ...

What is the best way to create subpages within a survey?

If I want to create a survey page on the web with multiple questions, but I am facing a challenge. I do not want to have several different pages and use a "Next Button" that links to another page. I am struggling to come up with ideas on how to implement ...

The request in Node.js was terminated

While using express and body-parser to transfer a large amount of data from one server to another, I encountered the following exception after some time: { "message": "request aborted", "code": "ECONNABORTED", "expected": 99010, "length": ...

JavaScript file system function not functioning according to its designated purpose

I have a basic script to write a JavaScript list to a JavaScript file. // Using the fs module to access // the writeFile function. var fs = require('fs'); // Start by overwriting any existing file with the beginning of the list fs.writeFile(&apo ...

The configuration error occurred for the `get` action due to an unexpected response. Instead of an object, an array was received

Despite numerous attempts, I am struggling to find a solution that works for me. In my Courses controller, I am using the Students service and Staff service to access my staff and student objects. My goal is to retrieve the staffs and students objects in o ...

Learn how to use an Angular Directive to automatically set the default value within an HTML Text box element. The code snippet provided below will guide you

I have encountered an issue with the code below. It seems to be working fine for changing the innerHTML of div and heading tags, but I am facing difficulties when trying to apply it to textboxes. @Component({ selector: 'app-root', template: ...

Retrieves MySQL SQL findings and converts them into a JSON structure

I'm in the process of integrating Typeahead.js into my website. The Typeahead.js plugin will retrieve data from a remote page that returns JSON, similar to: http://example.org/search?q=%QUERY Here's the PHP code I've written for my site: ...

What causes the unexpected behavior of JQuery's .animate() function?

I am currently working on a project that involves creating a div element for the purpose of dragging and dropping files. My goal is to have the height of the div increase when a file is dragged into it, and decrease when the file is dragged out. To achiev ...

Establishing numerous websocket connections within a singular application

I am looking to conduct load testing on our websocket service. Is there a method to establish multiple websocket connections from one workstation? My attempt with npm ws and websocket modules in conjunction with NodeJS was successful for a single connecti ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Tips for sending a structured search query to the findOne() function in MongoDB with Node.js

I have a Restful service built with node.js that takes user input to create a query string for MongoDB. However, whenever I try to pass this query to findone() in MongoDb and call the service, it displays a "query selector must be an object" message in the ...

Excessive tab usage in headless Chrome driver on Selenium with Python in Linux causes connection loss

Running my headless chrome driver on an AWS EC2 instance has been smooth sailing until I hit around 8 tabs, at which point the driver becomes "Unreachable". This issue doesn't occur on MAC and htop reveals that despite having ample memory available (a ...

jqGrid - Error when the length of colNames and colModel do not match!

Whenever I implement the code below, it triggers an error saying "Length of colNames and <> colModel!" However, if isUserGlobal is false, no errors occur. The version of jqGrid being used is 4.5.4 receivedColModel.push({name:'NAME', index: ...

Problem with jQuery Window Resize Trigger Not Reactivating

I am facing a challenge in integrating a slider within multiple jquery tabs. As the slider requires specific width and height to display correctly, I have to trigger a window resize event when the tabs are switched. Surprisingly, the code I implemented onl ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

Click outside to toggle dropdown and hide it

My dropdown menu is currently working, but I would like it to close when I click outside of it. I've tried various solutions provided in other posts, but I just can't seem to get it right. Can someone please help me figure out what I am missing? ...