Implementing waitFor functionality with phantomjs-node

前端 未结 3 1728
囚心锁ツ
囚心锁ツ 2021-01-02 01:10

I have tried and tested - with success - the phantomjs example waitFor. However, I am having difficulty implementing it via the phantomjs-node module primarily because

3条回答
  •  执念已碎
    2021-01-02 01:29

    I've written an alternative for phantomjs-node called phridge. Instead of turning all function calls and assignments into async operations it just executes the whole function inside PhantomJS.

    I think your problem could be accomplished like this:

    phridge.spawn()
        .then(function (phantom) {
            return phantom.openPage(url);
        })
        .then(function (page) {
            return page.run(selector, function (selector, resolve, reject) {
                // this function runs inside PhantomJS bound to the webpage instance
                var page = this;
                var intervalId = setInterval(function () {
                    var hasBeenFound = page.evaluate(function (selector) {
                        return Boolean(document.querySelector(selector));
                    }, selector);
    
                    if (hasBeenFound === false &&
                        /* check if there is still some time left  */) {
                        // wait for next interval
                        return;
                    }
    
                    clearInterval(intervalId);
    
                    if (hasBeenFound) {
                        resolve();
                    } else {
                        reject(new Error("Wait for " + selector + " timeout"));
                    }
                }, 100);
            });
        })
        .then(function () {
            // element has been found
        })
        .catch(function (err) {
            // element has not been found
        });
    

提交回复
热议问题