Cannot click on elements programmatically in WhatsApp web

Viewed 1316

Why it is not possible to click on any element on WhatsApp web (https://web.whatsapp.com) using JavaScript .click() method? The steps I am taking are mentioned below:

  1. Assuming that the QR code verification is completed, visit https://web.whatsapp.com
  2. Find the search bar that says Search or start new chat, which is an input element, and trigger .click() on it.

I am able to find the search input field because it has a unique title value Search or start new chat, but when I try to click it in Chrome's DevTools console, nothing happens.

First I thought that I might be firing click on the wrong element. To be sure, I installed the Katalon Recorder automation extension on Chrome. Then I recorded the steps taken (browse to WhatsApp web, click on search box). Playing the routine in Katalon clicks the search box as expected. I copied the Xpath expression recorded by Katalon and pasted the whole thing to document.evaluate(). Turns out, it was the same input element captured by querySelectorAll.

In the browser-console, I'm running this code:

let xPath = "(.//*[normalize-space(text()) and normalize-space(.)='Search or start new chat'])[1]/following::input[1]";
let result = document.evaluate(xPath, document);
let searchBox = result.iterateNext();
searchBox.click();

So, do you have any idea why .click() is not working on WhatsApp web? I would also like to know what Katalon does differently - allowing it to click on the desired element. Can I do that in a headless browser?

1 Answers

So the solution is on triggering an event via js and a new Event() For this to work you will need to trigger a focus event followed by a click event.

let xPath = "(.//*[normalize-space(text()) and normalize-space(.)='Buscar o empezar un chat nuevo'])[1]/following::input[1]";
let result = document.evaluate(xPath, document);
let searchBox = result.iterateNext();

var eventFocus = new Event('focus');
var eventClick = new Event('click');
searchBox.dispatchEvent(eventFocus);
searchBox.dispatchEvent(eventClick);

Also I had to change Search or start new chat to spanish, my default language Buscar o empezar un chat nuevo. So something you can think of to improve your code. Hope this helps :)

Related