9

I want to simulate click on GMail COMPOSE button using JS without JQuery.

Here is button:

<div class="T-I J-J5-Ji T-I-KE L3" role="button" tabindex="0" gh="cm" 
style="-webkit-user-select: none;">COMPOSE</div>

Here is my js:

var element = document.getElementsByClassName('T-I-KE')[0];
element.click();

Result:undefined in all browsers

Image: https://i.stack.imgur.com/Mkscf.png

Already tried that:

var event = document.createEvent("MouseEvent");
event.initEvent("click",true,true);
var element=document.getElementsByClassName("T-I-KE")[0];
element.dispatchEvent(event);

Result:true. But nothing happens.

Image: https://i.stack.imgur.com/H3KSH.png

Mikolaytis
  • 921
  • 1
  • 12
  • 27

3 Answers3

12

After two days i am finally got an answer!

That button listens mouseDown and mouseUP events. Working code:

var down = new MouseEvent('mousedown');
var up = new MouseEvent('mouseup');
var elem = document.getElementsByClassName("T-I-KE")[0];
elem.dispatchEvent(down);
elem.dispatchEvent(up);
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
Mikolaytis
  • 921
  • 1
  • 12
  • 27
  • Refer to http://stackoverflow.com/questions/10213703/how-do-i-view-events-fired-on-an-element-in-chrome-web-developer on how to monitor events -- it will save you a lot of head scratching :). – thdoan Mar 01 '16 at 07:26
  • 3
    This works well for some buttons (like 'compose' or 'more') but has any effect on other buttons (like 'settings' in the right corner). After few hours of monitoring events I gave up. Anyone is able to click 'settings' programatically? – Edvard Rejthar Dec 01 '17 at 16:59
-1

The function getElementsByClassName(classString) will return the elements with the class of exactly the string that you pass to it. Try using querySelector, like this

document.querySelector(".T-I-KE");

That will return the first element with the class T-I-KE. If you want ALL the elementes with that class, call the function querySelectorAll instead

Yerko Palma
  • 12,041
  • 5
  • 33
  • 57
  • 1
    I don't have issues with selecting a button. I can't simulate click on it. Here is your example: http://i.imgur.com/riFnz1o.png Result the same. – Mikolaytis Feb 12 '15 at 14:36
-1
function click(tagNode) {
    const down = new MouseEvent('mousedown', {
        bubbles: true
    });
    const up = new MouseEvent('mouseup', {
        bubbles: true
    });
    tagNode.dispatchEvent(down);
    tagNode.dispatchEvent(up);
}