I'm writing a Chrome extension, and I have the following function for grabbing data from a URL:
function getContentFromURL(theUrl) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.timeout = 10;
xmlhttp.open('GET', theUrl, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
// console.log(xmlhttp.responseText);
return xmlhttp.responseText;
}
};
xmlhttp.send();
}
In another file I have var someHTMLContent = getContentFromURL(chrome.extension.getURL('client/views/aPage.html'));
.
When I output the xmlhttp.responseText
(see commented line), I get the expected data, but when I log out someHTMLContent
, it returns undefined
. After some experimentation, I discovered that if I set the async
flag to false and return the responseText after xmlhttp.send()
, my code works. I don't want to do that, however, because it's detrimental to the user experience.
Can someone shed some light on this for me?
EDIT: I tried using the answer here, and came up with the following code:
function getContentFromURL(theUrl) {
return new Promise(function(resolve, reject) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
if (xmlhttp.status === 200) {
resolve(xmlhttp.responseText);
} else {
reject(xmlhttp.statusText);
}
};
xmlhttp.onerror = function() {
reject(console.error('Network Error'));
};
xmlhttp.open('GET', theUrl);
xmlhttp.send();
});
}
and
var someHTMLContent = getContentFromURL(chrome.extension.getURL('client/views/aPage.html')).then( function(result) {
return result;
}).catch(function(err) {
console.error(err);
});
Now, however, I get an ERR_EMPTY_RESPONSE
after about 30 seconds.