PhantomJS - onLoadFinished无理由地调用了两次

时间:2018-01-03 13:18:04

标签: javascript phantomjs

这是我的代码:

var system = require('system');
var page = require('webpage').create();
var server = require('webserver').create();
var system = require('system');
var someUrl = "http://sportfun.bg";    
var port = 3000;
//Screen resolution
page.viewportSize = {
    width: 1920,
    height: 1080
};
//User agent
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
page.onConsoleMessage = function(msg) {
    system.stderr.writeLine('Console: ' + msg);
};
var service = server.listen(port, function (request, response) {
    //console.log('Request received at ' + new Date());
    //console.log("Request" + JSON.stringify(request.post));
    var POST = request.post;
    //console.log("Bank:" + POST.bank);
    // TODO: parse `request` and determine where to go

    var step = 0;

    page.open(someUrl, function (status) {
        if (status !== 'success') {
            console.log('Unable to post!');
        } else {
            console.log("Here0");    
            page.onLoadFinished = function(status) {
                if(status === "success"){
                    console.log("Here 1"); 
                    response.statusCode = 200;
                    response.headers = {
                        'Cache': 'no-cache',
                        'Content-Type': 'text/plain;charset=utf-8'
                    };

                    // TODO: do something on the page and generate `result`
                    response.write("We good");
                    //console.log(page.content);
                    response.close();  
                }
            };

        }
    });


});
console.log("Server started!");

我正在使用PhantomJS 2.1.1。

当我启动服务器并在控制台中向它发送一个帖子请求时,我看到了一件奇怪的事情:

Server started!
Here0
Here 1
Here 1

为什么我实际上应该一次加载页面时看到两次Here 1? 是否有任何理由,我该如何解决?

1 个答案:

答案 0 :(得分:1)

如果通过iframe嵌入多个小部件(如Facebook小部件或Google地图),则会发生onLoadFinished的多次回调。您可以通过将对这些网站的呼叫列入黑名单来摆脱它们:

block_urls = ['gstatic.com', 'google-analytics.com', 'tawk.to', 'perdeta.net', 'facebook.net', 'facebook.com'];

page.onResourceRequested = function(requestData, request){
    for(url in block_urls) {
        if(requestData.url.indexOf(block_urls[url]) !== -1) {
            request.abort();
            console.log(requestData.url + " aborted");
            return;
        }
    }            
}

如果您实施此解决方案,您会注意到“此处1”不再打印。这是因为第一个onLoadFinished实际上甚至在之前 page.open被解雇,但是只有在调用page.open之后才创建它。

如果你想真正使用page.onLoadFinished,你应该在page.open之前对其进行decalre。