I'm trying to develop a new Chrome extension based on its last version (MV2), and trying to send a request to a remote server using a fetch request from the service worker. The fetch request should be fired once the popup is shown.
The problem is that I get a Failed to fetch error. I doubt that it's a cors error, as this flow (with some changes made due to the upgrade from version 2 to version 3 of the manifest) worked before.
The manifest:
{ "manifest_version": 3, "name": "Test", "description": "Test", "version": "1.0", "options_ui": { "page": "options.html" }, "author": "Eyal", "action": { "default_icon": { "16": "test.png" }, "default_popup": "popup.html" }, "background": { "service_worker": "eventsPage.js" }, "web_accessible_resources": [ { "resources": ["*.png"], "matches": ["*://*/*"] } ], "permissions": ["activeTab", "storage"], "host_permissions": ["<all_urls>"] }The popup.js code:
document.addEventListener("DOMContentLoaded", () => { chrome.runtime.sendMessage( { type: "configuration", }, function (response) { res = response.res; page = response.page; console.log(res); if (page == "main") { main_page(res); } else { showPage("welcome"); } } ); });Where the configuration (server url and api key) are stored in chrome storage after setting it in the options page. The helper functions are all working.
The service worker code:
function send(method, uri, body, callback) { getConfiguration((conf) => { if (!isConfigured(conf)) { if (callback) { callback({ ok: false, data: "Server options not set" }); } return; } const req = getFullRequestUrl(conf.server, uri); let p = { headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: conf.apiKey, }, cache: "no-cache", method: method, }; fetch(req, p) .then((response) => { if (response.ok) { return response.json(); } throw new Error(response.statusText); }) .then((data) => { if (callback) { callback({ ok: true, data: data }); } }) .catch((error) => { if (callback) { callback({ ok: false, data: error.message }); } }); }); } chrome.runtime.onMessage.addListener((data, sender, sendResponse) => { let responseObj = null; if (data.type === "configuration") { getConfiguration((conf) => { if (isConfigured(conf)) { send("GET", "test", null, (res) => { sendResponse({ res: res, page: "main" }); }); } else { sendResponse({ res: null, page: "welcome" }); } }); } return true; });Tried changing the host permissions field to be the exact URL of the server - didn't work.
Tried to make the fetch directly from the listener - didn't work.