How do I click an element in PhantomJS?
page.evaluate(function() {
document.getElementById(\'idButtonSpan\').click();
});
This gives
Hope the following method will be useful. It worked for me in version 1.9
page.evaluate(function(){
var a = document.getElementById("spr-sign-in-btn-standard");
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
waitforload = true;
});
This worked for me. Hope this will be useful for others also
use simple JavaScript with evaluate
, something like this:
page.evaluate(function() {
document.getElementById('yourId').click();
});
.click()
is not standard. You need to create an event and dispatch it:
function click(el){
var ev = document.createEvent("MouseEvent");
ev.initMouseEvent(
"click",
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
el.dispatchEvent(ev);
}
For those using JQuery, the JQuery UI created a utility to simulate these: jquery-simulate. I use this in PhantomJS and Chrome
$ele..simulate( "click" );
Double clicks are also possible with PhantomJS.
This is adapted from the answer of stovroz and triggers a native dblclick
including the mousedown
, mouseup
and click
events (two of each).
var rect = page.evaluate(function(selector){
return document.querySelector(selector).getBoundingClientRect();
}, selector);
page.sendEvent('doubleclick', rect.left + rect.width / 2, rect.top + rect.height / 2);
The following two ways only trigger the dblclick
event, but not the other events that should precede it.
Adapted from this answer of torazaburo:
page.evaluate(function(selector){
var el = document.querySelector(sel);
var ev = document.createEvent("MouseEvent");
ev.initMouseEvent(
'dblclick',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
el.dispatchEvent(ev);
}, selector);
Adapted from this answer of Jobins John:
page.evaluate(function(selector){
var el = document.querySelector(sel);
var e = document.createEvent('MouseEvents');
e.initMouseEvent('dblclick', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
el.dispatchEvent(e);
}, selector);
Full test script