I can’t get this to work – I’m following the actual docs, as well as this example:
I’m simply trying to GET json data, formatted to the browser screen like so: {“name”:”value”}, from a URL, but get a “null” value returned when I alert.
My manifest.json:
{
"name": "Chrome Extension",
"version": "1.0",
"description": "Does a GET request cross-domain.",
"background_page": "plugin.html",
"permissions": [
"tabs",
"http://*"
],
"browser_action": {
"default_title": "",
"default_icon": "icon.ico"
}
}
My plugin.html:
<html>
<head>
<script>
function fetchData(callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function (data) {
if (req.readyState == 4) {
if (req.status == 200) {
callback(req.responseText);
} else {
callback(null);
}
}
};
var url = 'http://foo/bar.php';
req.open('GET', url, true);
req.send();
};
function onRequest(request, sender, callback) {
if (request.action == 'fetchData') {
fetchData(callback);
}
};
chrome.extension.onRequest.addListener(onRequest);
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({url: 'index.html'});
});
</script>
</head>
</html>
My index.html:
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script type="text/javascript">
function onReturn(data) {
alert('Data ' + data);
};
chrome.extension.sendRequest({'action' : 'fetchData'}, onReturn);
</script>
</body>
</html>
Duh. chrome extension – ip domain permissions