How do I click an element in PhantomJS?
page.evaluate(function() {
document.getElementById(\'idButtonSpan\').click();
});
This gives
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