有没有办法从页面上下文中的幻影上下文中收听一个事件? [英] Is there a way to listen to an event in the phantom context from page context?
问题描述
page.evaluate()
之外)知道异步进程已经完成。 我不想使用 setTimeout
和 setInteval
等待并在幻影中连续检查
正是这个 onCallback
和 window.callPhantom()
对用于。
因此,如果您在页面上下文中有一个异步调用,就像AJAX请求一样,您可以执行以下操作:
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();
});
另一种使用此方法是将调用添加到生产JavaScript以使测试更容易。如果您正在编写Web应用程序,那么找到一个选择器有时会变得复杂,这表示页面何时完全加载。为了使测试这样的应用程序更容易,您可以在页面中看到类似的JavaScript:
finishOffPage(function callback(){
if(typeof window.callPhantom ===function){
window.callPhantom({type:loadFinished});
}
});
然后你可以这样写测试:
page.onCallback = function(data){
if(data.type ===loadFinished){
//做一些测试
}
};
page.open(url);
这是一个例子,可以动态添加这样的事情:等待角色应用程序从幻影脚本完全呈现
For example: I open a page with PhantomJS, evaluate an asynchronous script (e.g. ajax). When it succeeds, I want to let the phantom context (outside of page.evaluate()
) know that the asynchronous process is finished.
I don't want to use setTimeout
and setInteval
to wait and check continously in the phantom context that the process is finished.
That is exactly what the onCallback
and window.callPhantom()
pair is for.
So, if you have an asynchronous call in the page context like 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();
});
The other way to use this is to add the call to your production JavaScript to make testing easier. If you're writing a web application it is sometimes complicated to find a selector which denotes when a page is fully loaded. To make testing such an application easier, you can have something like this in the page JavaScript:
finishOffPage(function callback(){
if (typeof window.callPhantom === "function") {
window.callPhantom({type: "loadFinished"});
}
});
Then you can write tests like this:
page.onCallback = function(data){
if (data.type === "loadFinished") {
// do some testing
}
};
page.open(url);
This is an example where such a thing can be added dynamically: wait for angular app to be fully rendered from phantom script
这篇关于有没有办法从页面上下文中的幻影上下文中收听一个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!