I'm new at PhantomJS and Javascript and I'm working on a script that test the loading time and I would like for it to detect whether there was a error 404/500 encountered while testing it and display and message in the console.log. The code goes like this:
var page = require('webpage').create(), t, address;
t = Date.now();
var testArray =
['someURL'];
function loadTest(testURL)
{
address = testURL;
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address' + address);
return;
}
});
}
for(var i = 0; i < testArray.length; i++)
{
loadTest(testArray[i]);
t = Date.now() - t;
console.log('Testing ' + testArray[i]);
console.log('Loading time ' + t + ' msec\n');
}
phantom.exit();
Help is much appreciated. Thanks
You might want to take a look at the onResourceReceived
callback to the page object, you should be able to get what you need from there. (API docs...)
This is a bit of a contrived example, and it is going to give back the status code for every resource retrieved as part of the request, but the first one will be the page itself (i.e., as opposed to supporting JS or CSS etc.):
var page = require('webpage').create();
page.onResourceReceived = function(res) {
if (res.stage === 'end') {
console.log('Status code: ' + res.status);
}
};
page.open('http://some.url/that/does-not-exist', function() {
phantom.exit();
});
Granted, this assumes that the server is going to actually return you a 404 (as opposed to a 200 masquerading as a 404, for example) -- but something along these lines should give you what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With