Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript click() doesn't work on some elements

I want to write some automation to website. Simply filling in forms and simulating clicks on elements. But for some elements JavaScript function click() doesn't work. For example it is on this page: http://www1.plus.pl/bsm/ If I do click() on "Wyślij" button, nothing happens. It is my command:

document.getElementsByClassName('tab-button')[0].click()

What is wrong? Why on other elements this function works?

like image 748
gumik Avatar asked Dec 15 '11 13:12

gumik


2 Answers

With yours help I found the solution:

var evt = document.createEvent('MouseEvents')
evt.initMouseEvent('mousedown', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.querySelectorAll('.tab-button')[0].dispatchEvent(evt)

Notice that it should be mousedown event rather than click. Some sites are done in a different way than others. Another important thing is 3rd parameter. It should be set to false (in this particular case). It sets cancelable value. Without this set to false it doesn't work.

Thank you for all answers!

like image 97
gumik Avatar answered Sep 19 '22 01:09

gumik


document.getElementsByClassName('tab-button')[0].dispatchEvent(event)

or

document.getElementsByClassName('tab-button')[0].fireEvent(event)

is the way you could do it... but trying it on the site, the 'click' event isn't bound to that element

EDITED See How to trigger event in JavaScript?

like image 36
paulslater19 Avatar answered Sep 20 '22 01:09

paulslater19