0

How come my function does not trigger the click event in phantomjs but it does in the chrome browser? On an li element specifically.

if(page.injectJs("./jquery-2.1.4.min.js") == false){
                    console.log("jquery Failed")
                }
                var sizePicked = page.evaluate(function(){
                    var Elements = document.getElementsByTagName("li");
                    for(i = 0; i < Elements.length; i++){
                        if (Elements[i].innerHTML.toLowerCase().indexOf("10") !== -1) {
                            $(Elements[i]).trigger("click");
                            break;
                        }
                    }
                })

This is the site I'm working on.

  • PhantomJS is version 1.9.x, I guess? – Vaviloff Dec 24 '15 at 00:40
  • Yes. It's 1.9.X the version right before 2 don't remember. –  Dec 24 '15 at 00:42
  • Have you checked this answer? http://stackoverflow.com/questions/15739263/phantomjs-click-an-element – Vaviloff Dec 24 '15 at 00:46
  • That person is trying to click with vanilla JS I'm clicking by wrapping it with jQuery like someone suggests in your link. –  Dec 24 '15 at 00:56
  • How do you think jQuery handles trigger("click") command? :) In the same vanilla js. The important thing is why won't it work in PhantomJS: `Patch since PhantomJS does not implement click() on HTMLElement. ` – Vaviloff Dec 24 '15 at 01:03
  • I don't that is true. I'm able to click on input buttons and trigger their onclicks events. Even from your link one comment says this "Wrapping el with jQuery gives you this defn of click. It'll work in your browser and in Phantom. $(el).click() – Bluu Jun 5 '13 at 2:02". My problem is when I use this with an li element it doesn't not trigger it's click events. –  Dec 24 '15 at 01:17

1 Answers1

3

In earlier PhantomJS versions (before 2.0.0) the underlying rendering engine does not support click() function on HTMLElement elements, but supports it on HTMLInputElement elements (inputs and buttons). That's why you can click() on input buttons but not on <li>s.

There are two possible solutions for your case:

A) Switch to PhantomJS 2

B) Use a shim to emulate click() function on HTMLElements. Just issue this evaluate at the top of your script and it will work for later evaluates.

page.evaluate(function(){
    if (!HTMLElement.prototype.click) {
        HTMLElement.prototype.click = function() {
          var ev = document.createEvent('MouseEvent');
          ev.initMouseEvent(
              'click',
              /*bubble*/true, /*cancelable*/true,
              window, null,
              0, 0, 0, 0, /*coordinates*/
              false, false, false, false, /*modifier keys*/
              0/*button=left*/, null
          );
          this.dispatchEvent(ev);
        };
    }        
});

Code from this solution

Community
  • 1
  • 1
Vaviloff
  • 16,282
  • 6
  • 48
  • 56