3

I don't understand how to close a modal or an element with PhanthomJS using sendEvent().

For example I tried to do it using the code below or using CaperJS click and clickLabel and many others things but it's not working.

var webpage = require('webpage').create();
var url  = 'http://sourceforge.net/';
webpage.viewportSize = { width: 1280, height: 800 };
webpage.render("test1.png");

webpage.onLoadFinished = function(status) {
    var coords = webpage.evaluate(function() {
        var firstLink = document.querySelector('a.btn');
        return {
            x: firstLink.offsetLeft,
            y: firstLink.offsetTop
        };
    });
    console.log(coords.x);
    console.log(coords.y);
    webpage.sendEvent('mousedown', coords.x, coords.y ,'left');
};


webpage.open(url,function(){
    webpage.render("test2.png");
    phantom.exit()
});

Here is the element I would like to skip. enter image description here

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
nono
  • 2,262
  • 3
  • 23
  • 32

1 Answers1

2

The offsetLeft and offsetTop only give the offset based on a parent element. You would have to sum all the element offsets up to the root node. That's at least what CasperJS does.

If this notice is static, you can determine the coordinates once and use them every time. Based on the screenshot (444,330) seems good as a replacement for coords.x, coords.y.

You can also simply use a synthentic mouse click as described here which is what CasperJS does, but in combination with a specific position. This is a plain synthetic click:

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

Also, you have two callbacks (onLoadFinished and function in webpage.open) for when the page is loaded. You should have only one, so you don't run into problems when when one of them is called. After you click, it's best to wait a little with setTimeout and let the page change before taking the screenshot.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • I don't have such a notice, so I can't test it. – Artjom B. Dec 21 '14 at 11:33
  • I tried using your approach, but it didn't work. I'm not sure I'm using it right. I replace the coordinates 0, 0, 0, 0, with mine(444,330).I tried others, using chrome dev tools. Could you give me an example closing an ordinary popup on a famous website. – nono Dec 26 '14 at 20:45
  • 1
    No, the coordinates of `initMouseEvent` should stay at 0. I meant that you should replace `coords.x, coords.y` for `444, 330`. Your script is strange, because you're using two onLoadFinished callbacks. I'm going to add this to the answer. – Artjom B. Dec 27 '14 at 09:32