有没有办法从页面上下文中的幻影上下文中收听一个事件? [英] Is there a way to listen to an event in the phantom context from page context?

查看:170
本文介绍了有没有办法从页面上下文中的幻影上下文中收听一个事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:我用PhantomJS打开一个页面,评估异步脚本(例如ajax)。当成功时,我想让幻影上下文( 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆