PhantomJS; click an element

前端 未结 11 838
借酒劲吻你
借酒劲吻你 2020-11-21 23:53

How do I click an element in PhantomJS?

page.evaluate(function() {
    document.getElementById(\'idButtonSpan\').click();  
});

This gives

11条回答
  •  迷失自我
    2020-11-22 00:32

    Double clicks are also possible with PhantomJS.

    Recommended

    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);
    

    Other ways

    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

提交回复
热议问题