I am trying to get the resulting JSON of https://tmi.twitch.tv/hosts?include_logins=1&host=105458682 with Javascript in a Chrome Extension, and so far I've had no success.
When I open it in a tab in Google Chrome, I get the following JSON response :
{"hosts":[{"host_id":105458682,"target_id":49780445,"host_login":"bobross","target_login":"misscoookiez"}]}
But if I try the same call from Javascript (and more precisely a Javascript used in a Chrome extension), I'll get the following error :
XMLHttpRequest cannot load https://tmi.twitch.tv/hosts?include_logins=1&host=113403683. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://deooplkjmdhjdicmeijmecmlnapmjhkd' is therefore not allowed access.
The code I used in Javascript is :
function callTwitch() {
var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open("GET", "https://tmi.twitch.tv/hosts?include_logins=1&host=105458682" , true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == "200") {
var data = JSON.parse(req.responseText);
// Do something with data
} else {
// Do something else
}
}
};
req.send(null);
};
After some googling, I found that it's a matter of CORS. Twitch didn't set Access-Control-Allow-Origin
to *
on their server and that's what seems to be blocking me. I tried many different ways of getting that JSON without any success.
I don't understand how and why this JSON is available when getting it from a tab and not when getting it from Javascript...
Can anyone help me ? Is there any way of getting this JSON from Javascript?
I eventually found how to do cross-origin XMLHttpRequest calls from a Chrome extension : I just had to add "https://tmi.twitch.tv/" to the permissions in manifest.json, and my original code started working. More about that here : https://developer.chrome.com/extensions/xhr