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") {
This is an example of how to add dynamic dynamics: wait for the angular application to complete from the phantom script
source share