I have used this page Cross-domain XMLHttpRequest using background pages to create a simple extension but I get following errors.
Unchecked runtime.lastError: The message port closed before a response was received.
I used this sample extension then added the contents https://github.com/SimGus/chrome-extension-v3-starter
forground.js
chrome.runtime.sendMessage({
method: 'POST',
action: 'xhttp',
url: 'https://www.stackoverflow.com/search',
data: 'q=something'
}, function (responseText) {
console.log(responseText);
});
service-worker.js
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 () {
// Do whatever you want on error. Don't forget to invoke the
// callback to clean up the communication port.
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; // prevents the callback from being called too early on return
}
});
manifest.json
{
"manifest_version": 3,
"name": "Chrome Extension v3 Starter",
"description": "A minimal example of a chrome extension using manifest v3",
"version": "0.0.1",
"icons": {
"16": "logo/logo-16.png",
"48": "logo/logo-48.png",
"128": "logo/logo-128.png"
},
"options_page": "settings/settings.html",
"action": {
"default_title": "Chrome Addon v3 Starter",
"default_popup": "popup/popup.html"
},
"permissions": [
"https://www.stackoverflow.com/search"
],
"host_permissions": [
"*://*/*"
],
"background": {
"service_worker": "service-worker.js"
},
"content_scripts": [{
"js": ["foreground.js"],
"matches": [ "http://*/*", "https://*/*" ]
}]
}