PhantomJS 2: detection of a click that did not trigger an event

I use PhantomJS 2 to click page elements. However, I do not know if clicking on these elements will trigger an event (for example, loading a page).

I would like to be able to handle both cases:

  • When a click on an element starts loading a page, I would like to wait until a new page is loaded.

  • If a click does not trigger an event, I would like to know that (without waiting for a long timeout).

In PhantomJS 1, I could just use closure like this:

function click(page, elem, callback) { var loading = false; page.set('onLoadStarted', function() { loading = true; }); page.set('onLoadFinished', function() { callback('click triggered page load'); }); triggerClick(page, elem); setTimeout(function() { if ( ! loading) { callback('click did not trigger page load'); } }, 100); } 

Here I close the variable loading , which acts as a “communication channel” between the event handlers and the function in setTimeout .

  • In case the click causes the page to load, the onLoadFinished handler will call the callback after the page loads.

  • If the click does not cause the page to load, the function in setTimeout will call the callback after 100 ms (which is acceptable).

This code works well under PhantomJS 1.

Under PhantomJS 2, unfortunately, event handlers for onLoadStarted and onLoadFinished can no longer access the loading variable (i.e. they no longer work as closures, as it seems).

So now I am wondering how I can achieve the same behavior in PhantomJS 2. Any ideas?

PS : I know that I need to install event handlers through page.property(...) in PhantomJS 2 instead of using page.set(...) , as in PhantomJS 1.

Change I use the node phantom package ( https://www.npmjs.com/package/phantom ) as a bridge between node and phantoms.

+7
javascript phantomjs
source share
1 answer

The solution for me was to actually drop the node bridge and use pure phantomjs instead. This leads to the following appropriate code for working as a charm, even with PhantomJS 2 :

 function click(page, elem, callback) { var loading = false; page.onLoadStarted = function() { loading = true; }; page.onLoadFinished = function() { callback('click triggered page load'); }; triggerClick(page, elem); setTimeout(function() { if ( ! loading) { callback('click did not trigger page load'); } }, 100); } 
0
source share

All Articles