Skip to content

Instantly share code, notes, and snippets.

@formido
Forked from JamesMGreene/phantomjs-xhr.js
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save formido/a13d7bcb813513e3b7df to your computer and use it in GitHub Desktop.
Save formido/a13d7bcb813513e3b7df to your computer and use it in GitHub Desktop.
var urls = [
/* Attempt to contact emacs web server from outer context */
'http://localhost:8080/skewer',
/* Wildcard CORS enabled - Works in PhantomJS 1.9.0 */
'http://updates.html5rocks.com',
/* CORS disabled - Fails in PhantomJS 1.9.0 (and every other version) */
'http://www.google.com',
/* Hack workaround? */
/*
function(httpGet, callback) {
phantom.page.settings = (phantom.page.settings || {});
phantom.page.settings.webSecurityEnabled = false;
phantom.page.setContent(phantom.page.content, phantom.page.url);
httpGet('http://www.google.com', callback);
console.log('waiting...');
}
*/
];
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
});
}
console.error(msgStack.join('\n'));
phantom.exit(1);
};
function httpGet(url, callback) {
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function() {
callback.call(xhr, null);
});
xhr.addEventListener('error', function(err) {
callback.call(xhr, err || new Error('HTTP error!'));
});
xhr.open('GET', url, false);
xhr.send(null);
}
var next = (function() {
var counter = 0;
var onCallback = function(err) {
console.log('GET ' + urls[counter]);
if (err) {
console.error('XHR Error!');
console.error('status: ' + this.status + ' (' + this.statusText + ')');
console.error('body:\n' + this.responseText + '\n');
}
else {
console.log('XHR Loaded');
console.log('status: ' + this.status + ' (' + this.statusText + ')');
console.log('body size: ' + this.responseText.length + '\n');
}
// Continue
counter++;
next();
};
// implementation: `next`
return function() {
var url = urls[counter];
if (url) {
if (typeof url === 'string') {
httpGet(url, onCallback);
}
else if (typeof url === 'function') {
url(httpGet, onCallback);
}
else {
throw new TypeError('urls[' + counter + '] was of an unexpected type: ' + (typeof url));
}
}
else {
phantom.exit(0);
}
}
})();
next();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment