Skip to content

Instantly share code, notes, and snippets.

@cburgmer
Created April 8, 2013 19:44
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 cburgmer/5339864 to your computer and use it in GitHub Desktop.
Save cburgmer/5339864 to your computer and use it in GitHub Desktop.
function get(url, mimeType, successCallback, errorCallback) {
var page = require("webpage").create(),
basePageMatch = /^(https?:)?\/\/[^\/]+/.exec(url),
basePage = basePageMatch ? basePageMatch[0] : url;
// HACK for relative protocol support
if (basePage.indexOf("//") === 0) {
basePage = "http:" + basePage;
}
page.open(basePage, function(status) {
if (status !== 'success') {
errorCallback("internal error");
return;
}
page.onConsoleMessage = function (msg) {
var params;
try {
params = JSON.parse(msg);
} catch (e) {
console.log("Error: Can't understand internal command " + msg + " : " + e);
return;
}
if (params.status === 'success') {
successCallback(params.content);
} else {
errorCallback();
}
};
page.evaluate(function (url, mimeType) {
var ajaxRequest = new window.XMLHttpRequest(),
repond = function (status, content) {
console.log(JSON.stringify({
status: status,
content: content
}));
};
ajaxRequest.addEventListener("load", function () {
if (ajaxRequest.status === 200 || ajaxRequest.status === 0) {
repond('success', ajaxRequest.response);
} else {
repond('error');
}
}, false);
ajaxRequest.addEventListener("error", function () {
repond('error');
}, false);
ajaxRequest.open('GET', url, true);
if (mimeType) {
ajaxRequest.overrideMimeType(mimeType);
}
try {
ajaxRequest.send(null);
} catch (err) {
repond('error');
}
}, url, mimeType);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment