使用$ .ajaxStop()来确定何时页面加载完成的CasperJS加载、页面、ajaxStop、CasperJS

2023-09-10 20:20:26 作者:惰性少年

到目前为止,在我的测试中写的CasperJS,我一直在使用waitForSelector()已经在页面上特定的元素,以确定是否一个页面完全加载(包括所有的异步Ajax请求)。我希望拿出等待页面加载更标准的方式,想知道是否以下是可能的吗?

So far in my tests written in CasperJS, I've been using waitForSelector() on page-specific elements to determine if a page has fully loaded (including all the async ajax requests). I was hoping to come up with a more standard way of waiting for page load and was wondering if the following was possible?

注入作为clientscript以下(include.js)

Inject as clientscript the following (include.js)

$(document).ajaxStop(function() {
    // Do something
})

根据jQuery的API ajaxStop的描述:注册一个​​处理函数,当所有Ajax请求已完成被称为

Description of ajaxStop according to jquery api: Register a handler to be called when all Ajax requests have completed.

定义casper.waitForLoad函数调用时会等待在上述code座的东西

Define a casper.waitForLoad function that when called would wait for the "something" in above code block

使用在测试的几个部分的功能​​。

Use the function in several parts of the test.

在另外任何提示//做事情的一部分也将是AP preciated :)我想使用的window.callPhantom功能在phantomJS,但我看它没有正式casperjs支持。

Also any tips on the // Do Something part would also be appreciated :) I was thinking about using the window.callPhantom feature in phantomJS but I'm reading that it's not officially supported in casperjs.

推荐答案

我会做这样的事情在include.js:

I would do something like this in include.js:

(function(){
    window._allAjaxRequestsHaveStopped = false;
    var interval;
    $(document).ajaxStop(function() {
        if (interval) {
            clearInterval(interval);
            interval = null;
        }
        interval = setTimeout(function(){
            window._allAjaxRequestsHaveStopped = true;
        }, 500);
    });
    $(document).ajaxStart(function() {
        window._allAjaxRequestsHaveStopped = false;
        if (interval) {
            clearInterval(interval);
            interval = null;
        }
    });
})();

此设置一个(希望是唯一的)变量的窗口对象,以后可以恢复。这还有待久一点柜面还有就是previous批次结束后另一个请求。

This sets a (hopefully unique) variable to the window object that can be later retrieved. This also waits a little longer incase there is another request after the previous batch ended.

在CasperJS你可能会做一些类似下面等待的请求状态的变化。这使用增加了新的功能,以卡斯珀对象,并使用 casper.waitFor()内部检查的变化。

In CasperJS you would probably do something like the following to wait for the change in the request status. This uses adds a new function to the casper object and uses casper.waitFor() internally to check the change.

casper.waitForAjaxStop = function(then, onTimeout, timeout){
    return this.waitFor(function(){
        return this.evaluate(function(){
            return window._allAjaxRequestsHaveStopped;
        });
    }, then, onTimeout, timeout);
};

和使用这样的:

casper.start(url).waitForAjaxStop().then(function(){
    // do something
}).run();

或者这样的:

or this:

casper.start(url).thenClick(selector).waitForAjaxStop().then(function(){
    // do something
}).run();