Is there a way to listen for an event in a phantom context from a page context?

For example: I open a page with PhantomJS, evaluate an asynchronous script (e.g. ajax). When this succeeds, I want the phantom context (outside page.evaluate() ) to know that the asynchronous process has completed.

I do not want to use setTimeout and setInteval to continuously wait and verify in the phantom context that the process is complete.

+6
source share
1 answer

This is exactly what for onCallback and window.callPhantom() for .

So, if you have an asynchronous call in the context of the page, for example, an AJAX request, you can do this:

 page.onCallback = function(data){ console.log("finished: " + data.text); phantom.exit(); }; page.evaluate(function(){ var xhr = new XMLHttpRequest(); xhr.open("GET", "/"); xhr.onreadystatechange = function () { var DONE = this.DONE || 4; if (this.readyState === DONE){ window.callPhantom({text: this.responseText}); } }; xhr.send(); }); 

Another way to use this is to add a call to your working JavaScript to simplify testing. If you are writing a web application, it is sometimes difficult to find a selector that indicates when the page is fully loaded. To make testing such an application easier, there might be something like this in a JavaScript page:

 finishOffPage(function callback(){ if (typeof window.callPhantom === "function") { window.callPhantom({type: "loadFinished"}); } }); 

Then you can write the tests as follows:

 page.onCallback = function(data){ if (data.type === "loadFinished") { // do some testing } }; page.open(url); 

This is an example of how to add dynamic dynamics: wait for the angular application to complete from the phantom script

+14
source

Source: https://habr.com/ru/post/983472/


All Articles