Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJS .click() not working

This code does not work:

var page = require('webpage').create();

page.open('http://www.ebay.com/', function() {
    console.log('Page loaded');
    page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() {
        console.log('jQuery included');
        page.render('C:/beforeclick.jpeg');
        console.log('Render 1');
        page.evaluate(function() {
            $('.btn-prim').click();
        });
        page.render('C:/afterclick.jpeg');
        console.log('Render 2');
    });
});

In fact $('.btn-prim').click() does not work, beforeclick.jpeg and afterclick.jpeg are the same. In browser console $('.btn-prim').click() works fine. Ebay here just for example, it does not work on other sites too. Please help me to solve the problem, I am novice in JavaScript.

like image 949
Ras2 Avatar asked Jun 01 '14 15:06

Ras2


2 Answers

This will give you a proper solution to the situation

page.evaluate(function(){
    var a = document.getElementById("target_element_to_be_clicked");
    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);
});

Hope this helps

like image 81
Jobins John Avatar answered Nov 18 '22 13:11

Jobins John


try this

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);
}
like image 21
user2497228 Avatar answered Nov 18 '22 11:11

user2497228