Javascript 使用CasperJS中的函数返回iframe内的链接

Javascript 使用CasperJS中的函数返回iframe内的链接,javascript,iframe,asynchronous,phantomjs,casperjs,Javascript,Iframe,Asynchronous,Phantomjs,Casperjs,我试图从iframe内部获取链接,并将其作为函数结果返回,我的简化代码如下所示: var casper = require("casper").create({ verbose: true, logLevel: "debug", webSecurityEnabled: false }); var url = casper.cli.get(0); casper.on('remote.message', function(msg) { this.echo(

我试图从iframe内部获取链接,并将其作为函数结果返回,我的简化代码如下所示:

var casper = require("casper").create({
    verbose: true,
    logLevel: "debug",
        webSecurityEnabled: false
});

var url = casper.cli.get(0);

casper.on('remote.message', function(msg) {
    this.echo(msg);
})

casper.start(url, function () {
    thelinks = getLinksFromIframes( casper );
    console.log("doesn't work:" + thelinks);
});

function getLinksFromIframes( context ) {
        var links = [];

        var iframes = context.evaluate( function() {
                var iframes = [];
                [].forEach.call(document.querySelectorAll("iframe"), function(iframe, i) { iframes.push( i ); });
                return iframes;
        });

        iframes.forEach( function( index ) {
            context.withFrame(index, function() {
                links = links.concat( this.getElementsAttribute( 'a', 'href' ) );
                console.log("works: " + links);
            });
        });

        return links;
}

casper.run(function() {
    console.log('done');
    this.exit();
});

问题是函数没有返回任何内容,我只能读取
withFrame
中的links变量,我知道还有其他方法可以获取链接,但代码是这种方式的,因为它是更复杂的分析嵌套iFrame的一部分,iFrame中的iFrame数量未知。是否有任何方法可以等待
withFrame
或允许我返回链接作为函数结果的东西?

这是意料之中的,因为
casper.withFrame
是一个异步步进函数。与以
然后
等待
开头的所有其他函数一样,它在CasperJS执行队列中安排一个步骤

当执行这些计划的步骤时(在当前步骤的末尾,即在您的情况下,
casper.start
然后
回调),
getLinksFromIframes
早已完成并返回空数组

有没有什么方法可以让我用iframe或其他东西来等待,让我将链接作为函数结果返回

不可以,但您可以使用回调:

function getLinksFromIframes( callback ) {
    var links = [];

    var iframes = this.evaluate( function() {
        var iframes = [];
        [].forEach.call(document.querySelectorAll("iframe"), function(iframe, i) { iframes.push( i ); });
        return iframes;
    });

    iframes.forEach( function( index ) {
        this.withFrame(index, function() {
            links = links.concat( this.getElementsAttribute( 'a', 'href' ) );
            console.log("works: " + links);
        });
    }, this);

    this.then(function(){
        callback.call(this, links);
    });
}

casper.start(url, function () {
    getLinksFromIframes.call(this, function(links){
        thelinks = links;
        console.log("Links: " + thelinks);
    });
})
.then(function(){
    console.log("Links later: " + thelinks);
})
.run();

阅读您的代码是有意义的,但是我没有得到任何console.log输出,这是完整的代码我正在测试输出看起来像这样我在localhost上测试一个简单的html,其中包括另一个带有iframe的html文件,第二个文件包含一些标记。抱歉,
this.withFrame
中的
this
未绑定到
casper
。我修复了它。是的,谢谢,我在编辑之前看到了你发布的第一个代码,添加了原始的上下文参数。现在一切正常了,我可以导航嵌套的iFrame,直到达到所需的级别并获取所有链接,非常感谢。