4

image of code using inspector

I want to click new chat button in http://web.whatsapp.com/ , and search a string.

Below is html tag that i want click:

<button class="icon icon-chat" title="New chat"></button>

and i use this javascript to click it:

document.querySelector('.icon.icon-chat').click()

but not work.

in same web, i use this code for clicking sending icon for send message and work:

 document.querySelector('.icon.icon-send.compose-btn-send').click()

2 Answers2

9

The React dev tools shows that the event handler is written to trigger on mousedown. So you have to fire mousedown event

Type this in console

function simulateMouseEvents(element, eventName) {
    var mouseEvent= document.createEvent ('MouseEvents');
    mouseEvent.initEvent (eventName, true, true);
    element.dispatchEvent (mouseEvent);
}

simulateMouseEvents(document.querySelector('.icon.icon-chat'), 'mousedown')
karthick
  • 11,998
  • 6
  • 56
  • 88
  • thanks karthick, its work. can you help me also to insert text into search contact and press enter? or do you have link refference that can i read about this for more? – Tutik Masfiyah Jun 07 '17 at 03:45
  • are you doing everything in developer console? – karthick Jun 07 '17 at 03:51
  • I don't know what is your purpose of you accessing the site. But you'll be able to do these kind of things only to some extent. Unless you know what the libraries are used , how the events are triggered and most important how the state of the application is managed. It's not possible to do a whole lot of things by simulation. For example: the search dropdown might be handled by some library, which only the developer of web.whatsapp will know. – karthick Jun 07 '17 at 03:59
  • you need to send a mouseup event after every mousedown or else this will only work once. simulateMouseEvents(document.querySelector('.icon.icon-chat'), 'mousedown'); simulateMouseEvents(document.querySelector('.icon.icon-chat'), 'mouseup'); – Gary Benade Jan 11 '18 at 06:22
  • WHOOOOOOOL THANK YOU! YOU ARE THE BEST! – Renan Coelho May 05 '18 at 00:06
1

Try this one

function triggerMouseEvent(node, eventType) {
    var event = document.createEvent('MouseEvents');
    event.initEvent(eventType, true, true);
    node.dispatchEvent(event);
}

triggerMouseEvent(document.getElementsByClassName("chat-title")[0], "mousedown");
SilverNak
  • 3,283
  • 4
  • 28
  • 44
Saladinost
  • 11
  • 1