Reputation: 13
I'm having a pretty frustrating problem with these firefox extensions. Specifically, the problem is that I cannot obtain and then use the data following the sendResponse of onMessage.addListener. Here is a short description:
browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
console.log("Message recived form background script:", message);
if (message.type === "call_LLM_Api") {
try {
console.log("Async logic...");
sendResponse({ result: "testtt", angelolo: "ok done" });
} catch (error) {
console.error("Error in back script", error);
sendResponse({ error: error.message });
}
return true;
}
});
async function ApiCall(data) {
try {
// cover browser.runtime.sendMessage in Promise
const response = await new Promise((resolve, reject) => {
browser.runtime.sendMessage(
{
type: "call_LLM_Api",
data: data,
},
(response) => {
if (browser.runtime.lastError) {
reject(new Error(browser.runtime.lastError.message));
} else if (!response) {
// Gestisce il caso in cui la risposta è undefined
reject(new Error("Response is undefined"));
} else if (response.error) {
reject(new Error(response.error));
} else {
resolve(response);
}
}
);
});
console.log("background response script:", response);
return response.result; // Ritorna il risultato
} catch (error) {
console.error("Error in message send:", error);
throw error; // Propaga l'errore
}
}
{
"manifest_version": 2,
"name": "Policy Analyzer",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"description": "Analyze the Privacy policy you are accepting by accessing a web page.",
"icons":{
"16": "icons/icon-16.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
},
"browser_action":
{
"default_icon":{
"16": "icons/icon-16.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
},
"default_title": "De Compile Privacy",
"default_popup": "popup/popup.html"
},
"permissions": [
"geolocation",
"tabs",
"activeTab",
"http://*/*",
"https://*/*",
"storage",
"webNavigation"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
So the problem seems to be that I can never get correct output from the calling function, it is always either undefined...
Error in message send: Error: Response is undefined
this problem seems quite serious and for this reason I ask you for support... Thanks to anyone who wants to contribute!!
Upvotes: 0
Views: 86
Reputation: 73766
The problem is that your function is async
, so it returns a Promise, not a literal true
.
In Firefox you can simply return the value, no need for sendResponse and return true
.
browser.runtime.onMessage.addListener(async (message, sender) => {
if (message.type === 'call_LLM_Api') {
return {result: 'testtt', angelolo: 'ok done'};
}
});
To enable the same code in Chrome you must polyfill it.
P.S. There's also no need to promisify browser
API, it's already promisified.
Upvotes: 0