У меня возникли проблемы с запросом http, используя chrome.runtime.sendMessage
(в моем сценарии содержимого) и chrome.runtime.onMessage.addListener
(на моей странице html html).Расширение Chrome: chrome.runtime.sendMessage и XMLHttpRequest();
Проблема здесь в том, что HTTP resquest не производится, и я никогда не получает обратный вызов responseText
правильно, всегда приходит как неопределенными в chrome.runtime.sendMessage
.
Итак, я хочу помочь, чтобы решить эту проблему.
Вот весь мой код:
Содержание сценария
chrome.runtime.sendMessage({
method: "GET",
action: "xhttp",
url: "http://www.example.net/echo.php?getecho",
data: ""
}, function(responseText) {
alert(responseText);
});
фона страницы HTML
<!DOCTYPE html>
<html style=''>
<head>
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.action == "xhttp") {
var xhttp = new XMLHttpRequest();
var method = request.method ? request.method.toUpperCase() : 'GET';
xhttp.onload = function() {
callback(xhttp.responseText);
};
xhttp.onerror = function() {
callback();
};
xhttp.open(method, request.url, true);
if (method == 'POST') {
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhttp.send(request.data);
return true;
}
});
</script>
</head>
<body>
</body>
</html>
PHP скрипт
<?php
if (isset($_GET["getecho"]))
{
echo "Hello i'm php script!";
}
?>
файл манифеста
{
"background": {
"page": "popup.html",
"persistent": true
},
"description": "Foo example",
"manifest_version": 2,
"name": "Foo",
"icons": {
"128" : "picture/wmp128.png",
"48" : "picture/wmp48.png"
},
"web_accessible_resources": [
"popup.js"
],
"content_scripts": [
{
"matches": ["<all_urls>", "*://*/*", "http://*/*", "https://*/*"],
"js": ["popup.js"],
"run_at": "document_end",
"all_frames": true
}
],
"permissions": [ "tabs", "background", "activeTab", "<all_urls>", "webNavigation", "webRequest", "http://*/*", "https://*/*", "*://*/*" ],
"version": "2.0"
}
HTML-встроенный код не допускается в хромовых расширениях. Используйте файл сценария js ([см. Документацию] (https://developer.chrome.com/extensions/event_pages#manifest)) вместо background.html. – wOxxOm
@wOxxOm, решился! Большое спасибо. –
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch –