Reputation: 3308
Here is my code:
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!");
I'm using PhantomJS 2.1.1.
When i launch the server and send a post request to it in the console i see strange thing:
Server started!
Here0
Here 1
Here 1
Why i see twice Here 1
when actually the page should be once loaded ?
Is there any reason about it and how can i fix it ?
Upvotes: 0
Views: 230
Reputation: 16838
Multiple callbacks of onLoadFinished
happen if there are multiple widgets embedded via iframe — like Facebook widgets or Google Maps. You can get rid of them by blacklisting calls to those sites:
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;
}
}
}
If you implement this solution you will notice that "Here 1" is not printed anymore. That is because the first onLoadFinished
is actually fired even before page.open
but you create it only after page.open
is called.
If you want to make real use of page.onLoadFinished you should decalre it even before page.open
.
Upvotes: 1